duan19850312 2019-03-16 13:05
浏览 17

如何创建通用请求验证中间件

What I want to achieve here is to create a very generic middleware called, Expects that actually validates the current request according to the parameters provided. It will raise a Bad Request if the required params are not present or are empty. In Python (Flask) this would be very simple like:

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

The definition of expects would look like this (a very minimal example):

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

I am just confused a little about how would I achieve that in Go. What I tried so far is:

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
        }
    }
}

and from main.go file:

func main() {
    var (
        endopintParams EndpointParamsRequired
    )

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

}

It actually works for the first time and validates the request, but after one valid request all the consecutive requests are successful even if the json does not contain the required param. Does that have anything to do with the global endopintParams I'm creating?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 matlab(相关搜索:紧聚焦)
    • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
    • ¥15 路易威登官网 里边的参数逆向
    • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
    • ¥50 需求一个up主付费课程
    • ¥20 模型在y分布之外的数据上预测能力不好如何解决
    • ¥15 processing提取音乐节奏
    • ¥15 gg加速器加速游戏时,提示不是x86架构
    • ¥15 python按要求编写程序
    • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入