0

我想在这里实现的是创建一个非常通用的中间件,Expects它实际上根据提供的参数验证当前请求。Bad Request如果所需的参数不存在或为空,它将引发 a 。在 Python (Flask) 中,这将非常简单,例如:

@app.route('/endpoint', methods=['POST'])
@expects(['param1', 'param2'])
def endpoint_handler():
    return 'Hello World'

的定义expects看起来像这样(一个非常小的例子):

def expects(fields):
    def decorator(view_function):

        @wraps(view_function)
        def wrapper(*args, **kwargs):
            # get current request data
            data = request.get_json(silent=True) or {}          

            for f in fields:
                if f not in data.keys():
                    raise Exception("Bad Request")

            return view_function(*args, **kwargs)

        return wrapper
    return decorator

我只是对如何在 Go 中实现这一点感到有些困惑。到目前为止我尝试的是:

type RequestParam interface {
    Validate() (bool, error)
}

type EndpointParamsRequired struct {
    SomeParam string `json:"some_param"`
}

func (p *EndpointParamsRequired) Validate() {
    // My validation logic goes here
    if len(p.SomeParam) == 0 {
        return false, "Missing field"
    }
}

func Expects(p RequestParam, h http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // Check if present in JSON request

        // Unmarshall JSON
        ...

        if _, err := p.Validate(); err != nil {
            w.WriteHeader(http.StatusBadRequest)
            fmt.Fprintf(w, "Bad request: %s", err)

            return
        }
    }
}

并从main.go文件中:

func main() {
    var (
        endopintParams EndpointParamsRequired
    )

    r.HandleFunc("/endpoint", Expects(&endopintParams, EndpointHandler)).Methods("POST")

}

它实际上是第一次工作并验证请​​求,但是在一个有效请求之后,所有连续请求都成功,即使 json 不包含所需的参数。endopintParams这与我正在创建的全球有什么关系吗?

4

0 回答 0