dongzhuanlei0768
2018-08-25 08:54
浏览 152
已采纳

在Go中验证HTTP请求的惯用方式

I need to validate that my http request has two parameters, Start and End. Currently, I set a default value that should not appear as either of the parameters and check for it along with other invalid values. However, this feels like a hack. What should be the proper way to do this?

Here is my code:

type Request struct {
    Start int `json: "start"`
    End int `json: "end"`
}


func HandlePost(w http.ResponseWriter, r *http.Request) {
    body , _ := ioutil.ReadAll(r.Body)
    reqData := Request{Start: -1, End: -1} // < whats the correct way to do this
    json.Unmarshal(body, &reqData)  

    if reqData.Start < 0 && reqData.End < 0 {
        w.WriteHeader(http.StatusBadRequest)
        return
    }
    // rest of the logic
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题