在Spring Boot应用程序中,可以使用server.servlet.context-path
属性为所有API资源设置基本路径。因此,实际的端点路径将为server.servlet.context-path + endpoint path
。
例如,如果server.servlet.context-path
设置为“/api/v1”,并且资源映射到“文章”,则该资源的完整路径为“/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
应该会导致“您好”响应。
关于go - 如何设置Go-chi的上下文路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63465062/