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 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?