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>
  • 写回答

1条回答 默认 最新

  • 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误