dongyuqi3808 2017-01-01 18:04
浏览 66
已采纳

go-json-rest:JSON有效负载为空

I'm trying to use go-json-rest to create RESTful APIs

I have this model struct:

type Todo struct {
    id   int
    name string
}

And I am trying to do a POST request to create an object of Todo type:

func CreateTodo(w rest.ResponseWriter, r *rest.Request) {

    body, _ := ioutil.ReadAll(r.Body)
    log.Println("body content is: ", string(body)) // here I can see {"name": "test1"}
    var todo Todo = Todo{}
    err := r.DecodeJsonPayload(&todo) // here the error shows JSON payload is empty
    defer r.Body.Close()

    if err != nil {
        log.Println("error in parsing json")
        rest.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    if todo.name == "" {
        rest.Error(w, "todo name is required", 400)
        return
    }
    lock.Lock()

    var nextId int = len(todos)
    //  todos[nextId] = todo
    todo.id = nextId // set its id
    todos = append(todos, todo)
    log.Println("num of todos: ", len(todos))
    lock.Unlock()

    w.WriteJson(&todo)
}

However, in the console of the POSTMAN client, the error shows:

{
  "Error": "JSON payload is empty"
}

I was wondering where might go wrong. Thanks

Edit: This should not be considered a duplicate question, because I am not even trying to use the json package to do marshalling/unmarshalling of JSON object. Instead I am using the rest.Request object (built in go-json-rest) to decode the json parameters as posted from client.

After much digging and search on this problem I found this answer below resolved my issue:

body, _ := ioutil.ReadAll(r.Body) will consume everything from the request body. So after removing this line, the json parsing works!

  • 写回答

1条回答 默认 最新

  • dqsxsmi3704 2017-01-02 14:49
    关注

    I was just being silly doing body, _ := ioutil.ReadAll(r.Body) before decoding the JSON parameters without really understanding what ioutil.ReadAll() does to the request body.

    As I quoted above in the edited post, ioutil.ReadAll() consumes everything in the request body, leaving nothing for the json decoder to parse. After removing the line body, _ := ioutil.ReadAll(r.Body), the json parsing works as expected.

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

报告相同问题?

悬赏问题

  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?