jjzjj

http - golang 服务器不解码 json(文字 false 中的无效字符 ' '(预期 'a')400")

coder 2024-07-12 原文

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

我正在使用 map 并将其作为 json 格式发送(avsUpload),原因是客户端可以拥有大量数据 n 而 struc 并不理想

客户端代码:

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"

最佳答案

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

关于http - golang 服务器不解码 json(文字 false 中的无效字符 ' '(预期 'a')400"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57945877/

有关http - golang 服务器不解码 json(文字 false 中的无效字符 ' '(预期 'a')400")的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  4. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  5. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  6. ruby - 默认情况下使选项为 false - 2

    这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb

  7. ruby - 如何模拟 Net::HTTP::Post? - 2

    是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou

  8. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  9. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  10. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

随机推荐