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

在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条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 用stata编写,数据集是Excel形式
      • ¥15 希望得到帮助,希望得到帮助
      • ¥15 Win7电脑开机出现硬件设置已更改
      • ¥15 vba代出现莫须有错误,都是一个个复制下来的为啥出错呢?
      • ¥15 /etc/vsftpd/vsftp.conf配置文件加了一行utf8_filesystem=YES之后,启动vsftpd报错
      • ¥15 W5100可以收广播,但是无法发出广播
      • ¥100 PCD点云排序和分割
      • ¥15 GG-CNN抓取数据集
      • ¥15 C++类和对象,多态性,继承,虚函数虚基类
      • ¥15 使用VS2019和Dev c++按%p输出地址,结果相差很大