2

在 Spring Boot 应用程序中,可以使用 property 为所有 API 资源设置基本路径server.servlet.context-path。所以实际的端点路径将是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) {...

谢谢

4

1 回答 1

1

这只是一个粗略的例子,希望能为您指明方向。如您所见.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”响应。

于 2021-02-08T11:03:10.010 回答