dsfw2154 2019-03-01 12:35
浏览 209

如何使用大猩猩/ mux golang从动态URL获取变量? 没有mux.vars()和正则表达式

I have an api that manages various company jobs, authorizes with bearer token I want from user to select one of the available task from the tasks list in order to use /api/tasks/{task} url like this: /api/tasks/checkaccount if the given task doesn't on the tasks list return not valid url. Is there a way that can handle this job in the validateMiddleware function?

My startApi function:

func (s *ApiServerStruct) Start(interval int) {
    router := mux.NewRouter()
    log.Println("Starting the Api")
    log.Printf("Api Listen: %s
", "127.0.0.1:8080")

    router.HandleFunc("/api/customer/newcustomer", ValidateMiddleware(s.newcustomer)).Methods("POST")
    router.HandleFunc("/api/customer/setsalary", ValidateMiddleware(s.SetSalary)).Methods("POST")
    router.HandleFunc("/api/customer/listcustomers", ValidateMiddleware(s.ListCustomers)).Methods("GET")
    router.HandleFunc("/api/customer/{login:0x[0-9a-fA-F]{40}}/newjob", ValidateMiddleware(s.NewJob)).Methods("POST")

    router.HandleFunc("/api/tasks/{task}/setnewtask", ValidateMiddleware(s.SetNewTask)).Methods("POST")

And a validateMiddleware function that checks whether given token in the header valid or not:

func ValidateMiddleware(next http.HandlerFunc) http.HandlerFunc {

    return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        authorizationHeader := req.Header.Get("authorization")
        if authorizationHeader != "" {
            bearerToken := strings.Split(authorizationHeader, " ")
            tempData := Data[bearerToken[1]]
            secretKey := tempData["secretkey"]
            if secretKey == "" {
                json.NewEncoder(w).Encode(Exception{Message: "Invalid authorization token"})
                return
            }
            if len(bearerToken) == 2 {
                token, error := jwt.Parse(bearerToken[1], func(token *jwt.Token) (interface{}, error) {
                    if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
                        return nil, fmt.Errorf("There was an error")
                    }
                    return []byte(secretKey), nil
                })
                if error != nil {
                    json.NewEncoder(w).Encode(Exception{Message: error.Error()})
                    return
                }
                if token.Valid {
                    context.Set(req, "decoded", token.Claims)
                    next(w, req)
                } else {
                    json.NewEncoder(w).Encode(Exception{Message: "Invalid authorization token"})
                }
            }
        } else {
            json.NewEncoder(w).Encode(Exception{Message: "An authorization header is required"})
        }
    })
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 帮我写一个c++工程
    • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
    • ¥15 关于smbclient 库的使用
    • ¥15 微信小程序协议怎么写
    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
    • ¥15 有了解d3和topogram.js库的吗?有偿请教