dongxie9169 2014-05-12 10:48
浏览 44
已采纳

有没有更简单的方法来使用net / http实现JSON REST服务?

I am trying to develop a REST service with net/http.

The service receives a JSON structure containing all the input parameters. I wonder if there is an easier and shorter way to implement the following:

func call(w http.ResponseWriter, r *http.Request) {
    if err := r.ParseForm(); err != nil {
        fmt.Printf("Error parsing request %s
", err)
    }
    var buf []byte
    buf = make([]byte, 256)
    var n, err = r.Body.Read(buf)
    var decoded map[string]interface{}
    err = json.Unmarshal(buf[:n], &decoded)
    if err != nil {
        fmt.Printf("Error decoding json: %s
", err)
    }
    var uid = decoded["uid"]
    ...
}

As you can see it requires quite a number of lines just to get to the extraction of the first parameter. Any ideas?

  • 写回答

1条回答 默认 最新

  • doujuan9698 2014-05-12 11:00
    关注

    You don't need to call r.ParseForm if the body of the request will contain a JSON structure and you don't need any URL parameters.

    You don't need the buffer either; you can use:

    decoder := json.NewDecoder(r.Body)
    

    And then:

    error := decoder.Decode(decoded)
    

    Putting it all together:

    func call(w http.ResponseWriter, r *http.Request) {
    
        values := make(map[string]interface{})
    
        if error := json.NewDecoder(r.Body).Decode(&values); error != nil {
            panic(error)
        }
    
        uid := values["uid"].(int)
    
    }
    

    It would be much nicer, though, if you could formally define the structure of the input that you're expecting in a struct type:

    type UpdateUserInformationRequest struct {
        UserId int `json:"uid"`
        // other fields...
    }
    

    And use an instance of this struct instead of a more general map.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?