From 86ab5edf4b9d08f4f6cac270be93004eb505c94d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20=C5=A0ediv=C3=BD?= Date: Thu, 1 Sep 2022 18:22:01 +0200 Subject: [PATCH] add path prefix #196. --- docs/changelog.md | 1 + docs/getting-started/configuration.md | 3 +++ server/internal/http/http.go | 6 ++++++ server/internal/types/config/server.go | 17 +++++++++++++---- 4 files changed, 23 insertions(+), 4 deletions(-) diff --git a/docs/changelog.md b/docs/changelog.md index 5d30683..b48e0d9 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -4,6 +4,7 @@ ### New Features - Added `m1k1o/neko:vivaldi` tag (thanks @Xeddius). +- Added `NEKO_PATH_PREFIX`. ## [n.eko v2.6](https://github.com/m1k1o/neko/releases/tag/v2.6) diff --git a/docs/getting-started/configuration.md b/docs/getting-started/configuration.md index 34008bc..062b416 100644 --- a/docs/getting-started/configuration.md +++ b/docs/getting-started/configuration.md @@ -134,6 +134,9 @@ nat1to1: #### `NEKO_PROXY`: - Enable reverse proxy mode, so that neko trusts `X-Forwarded-For` headers. - e.g. `false` +#### `NEKO_PATH_PREFIX`: + - Path prefix for HTTP requests. + - e.g. `/neko/` ### Expert settings diff --git a/server/internal/http/http.go b/server/internal/http/http.go index 533da49..bb70243 100644 --- a/server/internal/http/http.go +++ b/server/internal/http/http.go @@ -30,6 +30,12 @@ func New(conf *config.Server, webSocketHandler types.WebSocketHandler) *Server { router.Use(middleware.RequestLogger(&logformatter{logger})) router.Use(middleware.Recoverer) // Recover from panics without crashing server + if conf.PathPrefix != "/" { + router.Use(func(h http.Handler) http.Handler { + return http.StripPrefix(conf.PathPrefix, h) + }) + } + router.Get("/ws", func(w http.ResponseWriter, r *http.Request) { err := webSocketHandler.Upgrade(w, r) if err != nil { diff --git a/server/internal/types/config/server.go b/server/internal/types/config/server.go index fcb4b91..51f0465 100644 --- a/server/internal/types/config/server.go +++ b/server/internal/types/config/server.go @@ -1,15 +1,18 @@ package config import ( + "path" + "github.com/spf13/cobra" "github.com/spf13/viper" ) type Server struct { - Cert string - Key string - Bind string - Static string + Cert string + Key string + Bind string + Static string + PathPrefix string } func (Server) Init(cmd *cobra.Command) error { @@ -33,6 +36,11 @@ func (Server) Init(cmd *cobra.Command) error { return err } + cmd.PersistentFlags().String("path_prefix", "/", "path prefix for HTTP requests") + if err := viper.BindPFlag("path_prefix", cmd.PersistentFlags().Lookup("path_prefix")); err != nil { + return err + } + return nil } @@ -41,4 +49,5 @@ func (s *Server) Set() { s.Key = viper.GetString("key") s.Bind = viper.GetString("bind") s.Static = viper.GetString("static") + s.PathPrefix = path.Join("/", path.Clean(viper.GetString("path_prefix"))) }