Som*_*esh 23 routes go url-mapping
本地的url参数是否有原生方式Go?
例如,如果我有一个URL:http://localhost:8080/blob/123/test我想将此URL用作/blob/{id}/test.
这不是关于寻找go图书馆的问题.我从基本问题开始,本身就提供了一个基本的设施来做这个本地.
Jac*_*cob 15
没有内置的简单方法可以做到这一点,但是,这并不难.
这是我如何做到这一点,而不添加特定的库.它放在一个函数中,以便您可以getCode()在请求处理程序中调用一个简单的函数.
基本上你只是分成r.URL.Path几部分,然后分析部分.
// Extract a code from a URL. Return the default code if code
// is missing or code is not a valid number.
func getCode(r *http.Request, defaultCode int) (int, string) {
p := strings.Split(r.URL.Path, "/")
if len(p) == 1 {
return defaultCode, p[0]
} else if len(p) > 1 {
code, err := strconv.Atoi(p[0])
if err == nil {
return code, p[1]
} else {
return defaultCode, p[1]
}
} else {
return defaultCode, ""
}
}
Run Code Online (Sandbox Code Playgroud)
Not*_*fer 11
好吧,没有外部库,你不能,但我可以推荐两个优秀的:
httprouter - https://github.com/julienschmidt/httprouter - 速度非常快,非常轻巧.它比标准库的路由器更快,并且每次调用创建0个分配,这在GCed语言中很棒.
Gorilla Mux - http://www.gorillatoolkit.org/pkg/mux - 非常受欢迎,界面友好,社区不错.
httprouter的示例用法:
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}
func main() {
router := httprouter.New()
router.GET("/hello/:name", Hello)
log.Fatal(http.ListenAndServe(":8080", router))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17351 次 |
| 最近记录: |