doubi12138
doubi12138
2019-01-05 15:02
浏览 13
已采纳

POST呼叫失败,并显示JSON [重复]

This question already has an answer here:

I have an API which accepts a request body like this:

The content-type is application/json.

{
  "firstname": "foo",
  "surname": "bar",
  "age": 10,
  "group":"test"
}

The request goes through when I use a client like Postman.

However, the same request fails from Go:

    type Student struct {
        firstname string
        surname   string
        age       int
        group     string
    }
    student:= Student{"foo", "bar", 10, "test"}
    b, err := json.Marshal(student)

    rest := restCall("POST", "http://api", b, "xyz123")

    func restCall(method string, url string, body []byte, token string)  {

        req, _ := http.NewRequest(method, url, bytes.NewReader(body))

        req.Header.Add("Authorization", token)
        req.Header.Add("content-type", "application/json")

        res, _ := http.DefaultClient.Do(req)

        defer res.Body.Close()
    }

I get an internal HTTP 500 error stating :

Mandatory parameter 'group' is missing.

But, I did pass it as you can see from my code.

</div>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 在这里有答案:

  • 在golang中解组json 1个答案 \ r

    我有一个API可以接受这样的请求正文:

    content-type是 应用程序/json。

    {
    “名字”:“ foo”,
    “姓氏”:“酒吧”,
    “年龄”:10,
    “  group“:” test“ 
    } 
       
     
     

    当我使用Postman这样的客户端时,请求会通过。

    但是 ,从Go发出的相同请求失败:

     类型Student结构{
    名字字符串
    姓氏字符串
    年龄int 
    组字符串
    } 
    学生:= 学生{“ foo”,“  bar“,10,” test“} 
    b,err:= json.Marshal(student)
     
     rest:= restCall(” POST“,” http:// api“,b,” xyz123“)
      
     func restCall(方法字符串,URL字符串,正文[] byte,令牌字符串){
     
     req,_:= http.NewRequest(方法,URL,字节,NewReader(body))
     
    请求。  Header.Add(“ Authorization”,令牌)
     req.Header.Add(“ content-type”,“ application / json”)
     
     res,_:= http.DefaultClient.Do(req)
     \  n延迟res.Body.Close()
    } 
       
     
     

    我收到一个内部HTTP 500错误,指出:

    必须 参数'group'丢失。

    但是,正如我从代码中看到的那样,我确实将其传递了。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshuiga2826
    dongshuiga2826 2019-01-05 15:27
    已采纳

    Your code has several issues: 1. Structure must have public fields and fields should be tagged. Then it will be serialized properly:

    type Student struct {
        Firstname string `json:"firstname"`
        Surname   string `json: "surname"`
        Age       int .  `json: "age"`
        Group     string `json: "group"`
    }
    

    2. Never ignore errors returned by method call. So you will not miss issues in your code:

    b, err := json.Marshal(student)
    if err != nil {
        fmt.Println(err)
    }
    

    And the same after calls of NewRequest and DefaultClient.Do

    点赞 评论

相关推荐