golang服务器无法解码json(字面意思为false(预期为'a')的无效字符''400“)

时间:2019-09-15 16:08:23

标签: http go request

我正在尝试从客户端向服务器发送文件和json数据,但是服务器未响应请求,并且无法解码json数据,但是文件被接收

我正在使用地图,并且将其以json格式(avsUpload)发送,原因是客户端可以拥有大量的数据n并且结构不是理想的

客户代码:

func UploadFile(file_up string,avsUpload map[string]string){

//get file
file, err := os.Open(file_up)
if err!=nil{
     fmt.Println(red(" ERROR ")+"open file",file,err)
     return
}

defer file.Close()

//get file info
fileInfo, err := os.Stat(file_up)
if err!=nil{
     fmt.Println(red(" ERROR ")+"geting file info",err)
     return
}

//create form
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", fileInfo.Name())
if err != nil {
     fmt.Println(red(" ERROR ")+"creating form file",err)
     return
}

io.Copy(part, file)
writer.Close()

//encode json, avsUpload as map
json.NewEncoder(body).Encode(avsUpload)

//create request
request, err := http.NewRequest("POST", "http://127.0.0.1:2047/ctrl/upload", body)
if err != nil {
    fmt.Println(red(" ERROR "),err)
    return
}

//add headers
request.Header.Add("Content-Type", writer.FormDataContentType())
request.Header.Add("Content-Type","application/json; charset=utf-8")
request.Header.Add("Authorization", "BEARER "+readKey())
request.Header.Add("Content-Length", strconv.FormatInt(request.ContentLength,10))

//create req 
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
    fmt.Println(red(" ERROR "),err)
    return
}
defer response.Body.Close()

content, err := ioutil.ReadAll(response.Body) 
if err != nil {
   fmt.Println(red(" ERROR "),err)
}

fmt.Println(" "+string(content))
}

捕获请求,我可以看到json数据正常发送

服务器代码:

func Upload(w http.ResponseWriter, r *http.Request){

//set header
w.Header().Set("Content-Type", "multipart/form-data")
w.Header().Set("Content-Type", "application/json")


//set max request size
r.Body = http.MaxBytesReader(w, r.Body, MaxFileSize)

fmt.Println("size>>> ",r.ContentLength)
//close conection if request is > MaxFileSize
if r.ContentLength > MaxFileSize  {
     http.Error(w, "File size is too large, max "+strconv.Itoa(FileSize)+" mb's\n", http.StatusExpectationFailed)
     log.Error(w, "File size is too large, max "+strconv.Itoa(FileSize)+" mb's", http.StatusExpectationFailed)
     return
} 

//create miltipart reader   
reader, err := r.MultipartReader()
if err != nil {
    log.Error(w, err.Error(), http.StatusBadRequest)
    return
}

// parse file form
p, err := reader.NextPart()
if err != nil && err != io.EOF {
    log.Error(w, err.Error(), http.StatusInternalServerError)
    return
}

//check if te variable file exist in form
if p.FormName() != "file" {
    http.Error(w, "file is expected\n", http.StatusBadRequest)
    log.Error(w, "file is expected", http.StatusBadRequest)
    return
}

//check file name length 
if len(p.FileName()) > 100 {
    http.Error(w, "file name is too long\n", http.StatusBadRequest)
    log.Error(w, "file name is too long", http.StatusBadRequest)
    return
}

//check if te filename contains spaces
var fileName string
if strings.Contains(p.FileName(), " "){
    fileName=strings.Replace(p.FileName(), " ", "_", -1)
}else{
    fileName=p.FileName()
}

//get user from id in token
_, claims, err := jwtauth.FromContext(r.Context()) 
if err != nil {
    log.Error(w, err.Error(), http.StatusBadRequest)
    return
}
user:=getUser(int(claims["id"].(float64)))

//create buffer   
buf := bufio.NewReader(p)

//upload file to user dir
f, err := os.OpenFile("test/"+user+"/tmpfile/"+fileName, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
   log.Error(w, err.Error(), http.StatusInternalServerError)
   return
}
defer f.Close()

//decode json from client
avsSelect:=make(map[string]string)
err = json.NewDecoder(r.Body).Decode(&avsSelect)
if err != nil {
      log.Error(w, err.Error(), http.StatusBadRequest)
      return
    }

//copy file to user dir
lmt := io.MultiReader(buf, io.LimitReader(p, MaxFileSize - 511))
fileSize, err := io.Copy(f, lmt)
if err != nil && err != io.EOF {
    http.Error(w, "File size is too large, max "+strconv.Itoa(FileSize)+" mb's\n", http.StatusExpectationFailed)
    log.Error(w, err.Error(), http.StatusInternalServerError)
    os.Remove(f.Name())
    return
}

defer p.Close()

//print conformation message
w.Write([]byte(fmt.Sprintf(green("SERVER: ")+"File "+fileName+" uploaded")))
fmt.Sprintf("File "+fileName+" uploaded")
log.Info("Size request: %#v\n", r.ContentLength)
log.Info("Size file uploaded: %#v\n",fileSize)
return
}

服务器为不同请求记录以下内容:

invalid character ' ' in literal false (expecting 'a')400
invalid character '¥' looking for beginning of value400"
invalid character '\\u0086' looking for beginning of value400"

2 个答案:

答案 0 :(得分:0)

您的JWT身份验证可能是一个问题,因为您忽略了来自jwtauth.FromContext的潜在错误。尝试在此处添加错误处理,看看是否有任何有用的信息。

答案 1 :(得分:0)

您的多部分构造似乎是错误的。您从文件创建了第一部分,但没有为json创建第二部分,而是将其直接解码到缓冲区中。相反,您应该使用writer.CreatePart创建一个新的部分,并将json数据写入从该位置返回的编写器中。