From 52b4cbcbdf894103e615f44163f4fe277aedbd13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20=C5=A0ediv=C3=BD?= Date: Fri, 28 Apr 2023 22:19:52 +0200 Subject: [PATCH] add path prefix to server. --- internal/config/server.go | 23 ++++++++++++++++------- internal/http/manager.go | 6 ++++++ 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/internal/config/server.go b/internal/config/server.go index 12ae00e4..44ba64ca 100644 --- a/internal/config/server.go +++ b/internal/config/server.go @@ -1,6 +1,8 @@ package config import ( + "path" + "github.com/spf13/cobra" "github.com/spf13/viper" @@ -8,13 +10,14 @@ import ( ) type Server struct { - Cert string - Key string - Bind string - Static string - PProf bool - Metrics bool - CORS []string + Cert string + Key string + Bind string + Static string + PathPrefix string + PProf bool + Metrics bool + CORS []string } func (Server) Init(cmd *cobra.Command) error { @@ -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") diff --git a/internal/http/manager.go b/internal/http/manager.go index 5450c697..eb986f93 100644 --- a/internal/http/manager.go +++ b/internal/http/manager.go @@ -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 {