wip webroot

This commit is contained in:
Felipe M. 2023-10-15 14:23:22 +02:00
parent 46c1a6ae8f
commit bb0664c2af
No known key found for this signature in database
GPG key ID: CCFBC5637D4000A8
3 changed files with 71 additions and 0 deletions

View file

@ -0,0 +1,23 @@
package middleware
import (
"fmt"
"strings"
"github.com/gin-gonic/gin"
)
// StripWebrootPrefixiddleware is a middleware that strips prefix from request path.
func StripWebrootPrefixMiddleware(prefix string) gin.HandlerFunc {
return func(c *gin.Context) {
// If prefix does not start with slash, add it
if !strings.HasPrefix(prefix, "/") {
prefix = "/" + prefix
}
fmt.Println(c.Request.URL.Path)
fmt.Println(prefix)
c.Request.URL.Path = strings.TrimPrefix(c.Request.URL.Path, prefix)
fmt.Println(c.Request.URL.Path)
c.Next()
}
}

View file

@ -0,0 +1,44 @@
package middleware
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func TestStripWebrootPrefixMiddleware(t *testing.T) {
prefix := "/prefix"
// Create a new router with the middleware
r := gin.New()
r.Use(StripWebrootPrefixMiddleware(prefix))
r.Use(func(ctx *gin.Context) {
fmt.Println("asd", ctx.Request.URL.Path)
})
// Define a test route
r.GET("/test", func(c *gin.Context) {
c.String(http.StatusOK, "Test")
})
// Create a test request
req, err := http.NewRequest("GET", prefix+"/test", nil)
if err != nil {
t.Fatal(err)
}
// Perform the request
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
// Check the response
if w.Code != http.StatusOK {
t.Errorf("Expected status code %d but got %d", http.StatusOK, w.Code)
}
if w.Body.String() != "Test" {
t.Errorf("Expected body %q but got %q", "Test", w.Body.String())
}
}

View file

@ -34,6 +34,10 @@ func (s *HttpServer) Setup(cfg *config.Config, deps *config.Dependencies) *HttpS
s.engine.Use(requestid.New())
if cfg.Http.RootPath != "" {
s.engine.Use(middleware.StripWebrootPrefixMiddleware(cfg.Http.RootPath))
}
if cfg.Http.AccessLog {
s.engine.Use(ginlogrus.Logger(deps.Log))
}