有没有一种方法可以检查HTTP请求中的无效查询参数?

时间:2020-01-02 22:44:03

标签: http go request net-http

我正在构建Go DELETE REST端点。此请求需要一组查询参数,该参数可过滤要删除的对象。

例如

enter image description here

到目前为止,如果有人发送类似请求

https://endpoint.blah.com/users?userId=7&age=24

我的实现删除了所有带有age=24的用户,并忽略了无效的userId123

我想实现一种检查请求中查询参数是否无效的方法。在这种情况下,请求中包含userId123应该返回Bad Request

我能想到的唯一方法是针对User结构字段对每个参数进行字符串匹配。我想知道一种更好的方法。

感谢所有帮助。将go版本go version go1.13.4 darwin/amd64net/http用于http框架。

2 个答案:

答案 0 :(得分:0)

在地图中记录有效参数:

var allowedDeleteParams = map[string]bool{"userid": true, "age": true}

编写一个函数来验证带有该映射的参数:

func checkParams(w http.ResponseWriter, r *http.Request, allowedParams map[string]bool) bool {
    r.ParseForm()
    for k := range r.Form {
        if _, ok := allowedParams[k]; !ok {
            http.Error(w, "Bad request", http.StatusBadRequest)
            return false
        }
    }
    return true
}

在这样的处理程序中使用它:

func handleDelete(w http.ResponseWriter, r *http.Request) {
  if !checkParams(w, r, allowedDeleteParams) {
     return
  }
  ...

答案 1 :(得分:0)

+1到@iLoveReflection。

此外,您真正需要的可能不是“检查userId123无效”。相反,您可能需要确保在函数开始处使用userId != ""。像这样:

func YourAPI(...) error {
    // 1. Parsing inputs to variables, usually into a struct
    // 2. Validate all required inputs are not nil, or invalid (eg. should not exceed maximum value or sth like that), for example:
    if p.UserID == "" {
        return error.New("Missing userId")
    }
    // 3. Start doing other works
}