go - 如何在 net/http 中编写/api/v1/users/id/{id}?

标签 go

例如,我想执行 /api/v1/users/id/{id}

目前,我有这个:

mux := http.NewServeMux()
mux.Handle("/api/v1/users", HandleUsersV1{db: db, mux: mux})
log.Fatal(http.ListenAndServe(fmt.Sprintf("%s%d", ":", portNumber), mux))

我要:

mux := http.NewServeMux()
mux.Handle("/api/v1", HandleV1{})

然后在 HandleV1 中:

mux.HandleFunc("/users/{id}", handler)

我知道 Gorilla Mux 可以用 PathPrefix 为我做这件事,但我更喜欢 net/http

最佳答案

标准 net/http 不支持动态路径段,因此 /{id} 不会像您想象的那样工作。至于前缀的东西,你可以用这个https://golang.org/pkg/net/http/#StripPrefix .

v1mux := http.NewServeMux()
v1mux.HandleFunc("/users/", handler)

mux := http.NewServeMux()
mux.Handle("/api/v1/", http.StripPrefix("/api/v1", v1mux))

log.Fatal(http.ListenAndServe(fmt.Sprintf("%s%d", ":", portNumber), mux))

关于go - 如何在 net/http 中编写/api/v1/users/id/{id}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51959339/

相关文章:

mongodb - 多条件获取 MongoDB 集合记录

unit-testing - 在 Go 单元测试中使用两个不同的模拟

Golang - 惯用的默认后备

go - 编码私钥得到错误 : asn1: structure error: tags don't match

sql - Golang pq sql 驱动程序 : get record ids after bulk import

http - 为什么我不能在 Go 中编写来自单独包的 HTTP 响应?

mongodb - 如何用Go驱动程序替换MongoDB中的文档?

go - Firebase Go 需要主机 "firebaseio.com"

go - Glide 或 dep 依赖问题,vendor 中的依赖不平坦

testing - 在非主程序包中运行类似主程序的程序