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 package config
import ( import (
"path"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
@ -12,6 +14,7 @@ type Server struct {
Key string Key string
Bind string Bind string
Static string Static string
PathPrefix string
PProf bool PProf bool
Metrics bool Metrics bool
CORS []string CORS []string
@ -38,6 +41,11 @@ func (Server) Init(cmd *cobra.Command) error {
return err 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") 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 { if err := viper.BindPFlag("server.pprof", cmd.PersistentFlags().Lookup("server.pprof")); err != nil {
return err return err
@ -61,6 +69,7 @@ func (s *Server) Set() {
s.Key = viper.GetString("server.key") s.Key = viper.GetString("server.key")
s.Bind = viper.GetString("server.bind") s.Bind = viper.GetString("server.bind")
s.Static = viper.GetString("server.static") s.Static = viper.GetString("server.static")
s.PathPrefix = path.Join("/", path.Clean(viper.GetString("server.path_prefix")))
s.PProf = viper.GetBool("server.pprof") s.PProf = viper.GetBool("server.pprof")
s.Metrics = viper.GetBool("server.metrics") 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 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.Route("/api", ApiManager.Route)
router.Get("/api/ws", WebSocketManager.Upgrade(func(r *http.Request) bool { router.Get("/api/ws", WebSocketManager.Upgrade(func(r *http.Request) bool {