Created
February 14, 2024 06:20
-
-
Save cheikhsimsol/0702c3a4a925b0e0427ed13970ceb962 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"net/http" | |
"net/http/httputil" | |
"net/url" | |
"github.com/gin-gonic/gin" | |
) | |
func launchSecondServer() { | |
router := gin.Default() | |
router.Use(func(ctx *gin.Context) { | |
ctx.JSON( | |
http.StatusOK, | |
gin.H{ | |
"Message": "Ok!", | |
"Path": ctx.Request.URL.String(), | |
}, | |
) | |
}) | |
router.Run(":8081") | |
} | |
func main() { | |
router := gin.Default() | |
// Define the target URL where the requests will be forwarded | |
target, _ := url.Parse("http://localhost:8081/base/") | |
// Create a reverse proxy | |
proxy := &httputil.ReverseProxy{ | |
Rewrite: func(r *httputil.ProxyRequest) { | |
log.Println("Forwarding:", r.In.URL.String()) | |
r.SetURL(target) | |
}, | |
} | |
// Middleware to modify the request URL before forwarding | |
router.Use(func(c *gin.Context) { | |
// Forward the request to the target server | |
proxy.ServeHTTP(c.Writer, c.Request) | |
}) | |
// start the second server | |
go launchSecondServer() | |
// Start the Gin server | |
router.Run(":8080") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment