2

In Spring Boot app a base path can be set for all API resources with a property server.servlet.context-path. So the actual endpoint path will be server.servlet.context-path + endpoint path.

For example, if server.servlet.context-path is set to "/api/v1", and a resource is mapped to "articles", the full path to that resource is "/api/v1/articles".

Is there something like this in go-chi? Or do I have to define a route with "full" path like

r.Route("/api/v1/articles", func(r chi.Router) {...

Thanks

Bing Qiao
  • 451
  • 1
  • 5
  • 14
  • https://github.com/go-chi/chi/blob/master/_examples/versions/main.go – mkopriva Aug 18 '20 at 08:54
  • 1
    This is unrelated to chi, per se. In Go, each router is also an HTTP handler. So the way to do this is to set a mux as a handler for the path you want. Then anything under that mux is in the "context" of that path. – Jonathan Hall Aug 18 '20 at 09:32

1 Answers1

1

This is just a rough example that will hopefully point you in the direction. As you can see .Mount() accepts a pattern and then a .Router. Play around with the two and figure out how you'd like to structure it.

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"))
}

Visiting localhost:8080/api/v1/user/hello should result in a "Hello" response.

Ari
  • 5,301
  • 8
  • 46
  • 120