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

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

  • dongqiang8683 2018-08-26 21:19
    关注

    Here's another way to validate structures using struct tags and pointers. Note that if 0 is a valid thing to pass, then this solution will not work. omitempty considers the 0 value to be empty. If you want this to work will considering 0 to be valid remove the pointers and modify the IsValid method

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Request struct {
        Start *int `json: "start,omitempty"`
        End   *int `json: "end,omitempty"`
    }
    
    func (r Request) IsValid() (bool, error) {
        if r.Start == nil {
            return false, fmt.Errorf("start is missing")
        }
    
        if r.End == nil {
            return false, fmt.Errorf("end is missing")
        }
    
        return true, nil
    }
    
    var (
        invalidStartb = `{"end": 1}`
        invalidEndb   = `{"start": 1}`
        valid         = `{"start": 1, "end": 1}`
    )
    
    func main() {
        var r Request
    
        _ = json.Unmarshal([]byte(invalidStartb), &r)
        fmt.Println(r.IsValid())
    
        r = Request{}
        _ = json.Unmarshal([]byte(invalidEndb), &r)
        fmt.Println(r.IsValid())
    
        r = Request{}
        _ = json.Unmarshal([]byte(valid), &r)
        fmt.Println(r.IsValid())
    
    }
    

    runnable version here https://goplay.space/#Z0eqLpEHO37

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗