doucuoyan0426 2019-09-13 01:21
浏览 48
已采纳

使用GO和大猩猩多路复用器进行动态路由查询

i'm setting up dynamic routes using gorilla mux, here's the routes.go code

type Route struct {
    Name        string
    Method      string
    Pattern     string
    Queries     []string
    HandlerFunc http.HandlerFunc
}

type Routes []Route

var vers = os.Getenv("API_VERSION")
var baseURL = "/api/" + vers + "/"

var authRoutes = Routes{
    Route{
        "GetAllUsers",
        "GET",
        baseURL + "users",
        []string{"maxperpage", "{maxperpage}", "setpage", "{setpage}"},
        ssoUserController.GetAllUsers,
    },
}

and i want to create dynamic Queries using slice like this:

func Handlers() *mux.Router {

//.....
//some code
//.....

    s := r.PathPrefix("/auth").Subrouter()
    s.Use(utils.JwtVerify)
    for _, authRoute := range authRoutes {
        var handler http.Handler
        var tamp = []string{}

        handler = authRoute.HandlerFunc
        handler = Logger(handler, authRoute.Name)
        for _, q := range authRoute.Queries {

            var addQuot = strconv.Quote(q)
            tamp = append(tamp, addQuot)

        }
        queries := strings.Join(tamp, ", ") //this code create string "maxperpage", "{maxperpage:[0-99]+}", "setpage", "{setpage:[0-99]+}"

        // fmt.Println(queries)
        s.
            Methods(authRoute.Method).
            Path(authRoute.Pattern).
            Queries(queries). // produce error panic: runtime error: invalid memory address or nil pointer dereference
            Name(authRoute.Name).
            Handler(handler)

    }

    return r
}

the code above is the router.go file it will route all the routes in routes.go file and when i put the queries slice it produce error

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x20 pc=0x77a750] 

please help to put dynamic url queries using gorilla mux

  • 写回答

1条回答 默认 最新

  • doumei9832 2019-09-13 01:58
    关注

    You're using Queries() wrong. It gets pairs of strings, not a single string. Using Queries(authRoute.Queries...) should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?