How to set context-path for go-chi?

Viewed 982

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

1 Answers

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.

Related