refactoring of code
This commit is contained in:
@@ -20,6 +20,7 @@ import (
|
||||
"fmt"
|
||||
"github.com/jkaninda/goma-gateway/internal/middlewares"
|
||||
"github.com/jkaninda/goma-gateway/pkg/logger"
|
||||
"github.com/jkaninda/goma-gateway/util"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
@@ -80,12 +81,7 @@ func (proxyRoute ProxyRoute) ProxyHandler() http.HandlerFunc {
|
||||
// Create proxy
|
||||
proxy := httputil.NewSingleHostReverseProxy(backendURL)
|
||||
// Rewrite
|
||||
if proxyRoute.path != "" && proxyRoute.rewrite != "" {
|
||||
// Rewrite the path
|
||||
if strings.HasPrefix(r.URL.Path, fmt.Sprintf("%s/", proxyRoute.path)) {
|
||||
r.URL.Path = strings.Replace(r.URL.Path, fmt.Sprintf("%s/", proxyRoute.path), proxyRoute.rewrite, 1)
|
||||
}
|
||||
}
|
||||
rewritePath(r, proxyRoute)
|
||||
// Custom transport with InsecureSkipVerify
|
||||
proxy.Transport = &http.Transport{TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: proxyRoute.insecureSkipVerify,
|
||||
@@ -105,3 +101,13 @@ func getNextBackend(backendURLs []string) *url.URL {
|
||||
backendURL, _ := url.Parse(backendURLs[idx])
|
||||
return backendURL
|
||||
}
|
||||
|
||||
// rewritePath rewrites the path if it matches the prefix
|
||||
func rewritePath(r *http.Request, proxyRoute ProxyRoute) {
|
||||
if proxyRoute.path != "" && proxyRoute.rewrite != "" {
|
||||
// Rewrite the path if it matches the prefix
|
||||
if strings.HasPrefix(r.URL.Path, fmt.Sprintf("%s/", proxyRoute.path)) {
|
||||
r.URL.Path = util.ParseURLPath(strings.Replace(r.URL.Path, fmt.Sprintf("%s/", proxyRoute.path), proxyRoute.rewrite, 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ func (gatewayServer GatewayServer) Initialize() *mux.Router {
|
||||
logger.Info("Block common exploits enabled")
|
||||
r.Use(middlewares.BlockExploitsMiddleware)
|
||||
}
|
||||
if gateway.RateLimit > 0 {
|
||||
if gateway.RateLimit != 0 {
|
||||
// Add rate limit middlewares to all routes, if defined
|
||||
rateLimit := middlewares.RateLimit{
|
||||
Id: "global_rate", //Generate a unique ID for routes
|
||||
@@ -242,7 +242,7 @@ func (gatewayServer GatewayServer) Initialize() *mux.Router {
|
||||
id = util.Slug(route.Name)
|
||||
}
|
||||
// Apply route rate limit
|
||||
if route.RateLimit > 0 {
|
||||
if route.RateLimit != 0 {
|
||||
rateLimit := middlewares.RateLimit{
|
||||
Id: id, // Use route index as ID
|
||||
Requests: route.RateLimit,
|
||||
|
||||
@@ -87,7 +87,7 @@ func MergeSlices(slice1, slice2 []string) []string {
|
||||
return append(slice1, slice2...)
|
||||
}
|
||||
|
||||
// ParseURLPath returns a URL path
|
||||
// ParseURLPath removes duplicated [//]
|
||||
func ParseURLPath(urlPath string) string {
|
||||
// Replace any double slashes with a single slash
|
||||
urlPath = strings.ReplaceAll(urlPath, "//", "/")
|
||||
|
||||
Reference in New Issue
Block a user