问题描述
在Spring Boot应用程序中,可以使用属性server.servlet.context-path
为所有API资源设置基本路径。因此,实际的端点路径将为server.servlet.context-path + endpoint path
。
例如,如果server.servlet.context-path
设置为“ / api / v1”,并且资源映射到“ articles”,则该资源的完整路径为“/api/v1/articles"。>
go-chi中是否有类似的东西?还是我必须定义一条具有“完整”路径的路线,例如
r.Route("/api/v1/articles",func(r chi.Router) {...
谢谢
解决方法
这只是一个粗略的例子,希望能为您指明方向。如您所见,.Mount()
接受一个模式,然后接受一个 .Router
。尝试使用两者并找出您想要如何构建它。
package main
import (
"github.com/go-chi/chi"
"net/http"
)
func main() {
r := chi.NewRouter()
r.Mount("/api",Versions())
http.ListenAndServe("localhost:8080",r)
}
func Versions() chi.Router {
r := chi.NewRouter()
r.Mount("/v1",V1())
// r.Mount("/v2",V2())
return r
}
func V1() chi.Router {
r := chi.NewRouter()
r.Mount("/user",User())
// r.Mount("/posts",Post())
return r
}
func User() chi.Router {
r := chi.NewRouter()
r.Route("/hello",func(r chi.Router){
r.Get("/",hello)
})
return r
}
func hello(w http.ResponseWriter,r *http.Request) {
w.Write([]byte("Hello"))
}
访问 localhost:8080/api/v1/user/hello
应该会得到“Hello”响应。