add path prefix to server.

This commit is contained in:
Miroslav Šedivý 2023-04-28 22:19:52 +02:00
parent c70c8217de
commit 52b4cbcbdf
2 changed files with 22 additions and 7 deletions

View File

@ -1,6 +1,8 @@
package config
import (
"path"
"github.com/spf13/cobra"
"github.com/spf13/viper"
@ -12,6 +14,7 @@ type Server struct {
Key string
Bind string
Static string
PathPrefix string
PProf bool
Metrics bool
CORS []string
@ -38,6 +41,11 @@ func (Server) Init(cmd *cobra.Command) error {
return err
}
cmd.PersistentFlags().String("server.path_prefix", "/", "path prefix for HTTP requests")
if err := viper.BindPFlag("server.path_prefix", cmd.PersistentFlags().Lookup("server.path_prefix")); err != nil {
return err
}
cmd.PersistentFlags().Bool("server.pprof", false, "enable pprof endpoint available at /debug/pprof")
if err := viper.BindPFlag("server.pprof", cmd.PersistentFlags().Lookup("server.pprof")); err != nil {
return err
@ -61,6 +69,7 @@ func (s *Server) Set() {
s.Key = viper.GetString("server.key")
s.Bind = viper.GetString("server.bind")
s.Static = viper.GetString("server.static")
s.PathPrefix = path.Join("/", path.Clean(viper.GetString("server.path_prefix")))
s.PProf = viper.GetBool("server.pprof")
s.Metrics = viper.GetBool("server.metrics")

View File

@ -36,6 +36,12 @@ func New(WebSocketManager types.WebSocketManager, ApiManager types.ApiManager, c
MaxAge: 300, // Maximum value not ignored by any of major browsers
}))
if config.PathPrefix != "/" {
router.UseBypass(func(h http.Handler) http.Handler {
return http.StripPrefix(config.PathPrefix, h)
})
}
router.Route("/api", ApiManager.Route)
router.Get("/api/ws", WebSocketManager.Upgrade(func(r *http.Request) bool {