我正在使用 gorilla mux 设置动态路由,这是 routes.go 代码
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,
},
}
我想像这样使用 slice 创建动态查询:
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
}
上面的代码是 router.go 文件,它将路由 routes.go 文件中的所有路由,当我放置查询 slice 时它会产生错误
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x20 pc=0x77a750]
请帮助使用 gorilla mux 进行动态 url 查询
最佳答案
您使用的 Queries()
有误。它得到成对的字符串,而不是单个字符串。使用 Queries(authRoute.Queries...)
应该有效。
关于go - 使用 GO 和 gorilla mux 的动态路由查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57916239/