Last active
June 12, 2024 20:02
-
-
Save ZeusMode/ca1b3d895eb7897fcf2eb0227f417ae8 to your computer and use it in GitHub Desktop.
Gin Golang handle multi sub-domain
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 ( | |
"net/http" | |
"strings" | |
"github.com/gin-gonic/gin" | |
) | |
// Create a subdomainHandler type that implements http.Handler interface | |
type subdomainHandler struct { | |
routers map[string]*gin.Engine // a map of routers for each subdomain | |
} | |
// Implement the ServeHTTP method for subdomainHandler | |
func (s *subdomainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
// Get the subdomain from the Host header | |
host := r.Host | |
subdomain := strings.Split(host, ".")[0] | |
// Check if there is a router for the subdomain | |
if router, ok := s.routers[subdomain]; ok { | |
// Use the router to handle the request | |
router.ServeHTTP(w, r) | |
} else { | |
// No router found, return an error | |
http.Error(w, "Not found", 404) | |
} | |
} | |
// Create a newSubdomainHandler function that returns a new subdomainHandler with the given routers | |
func newSubdomainHandler(routers map[string]*gin.Engine) *subdomainHandler { | |
return &subdomainHandler{routers: routers} | |
} | |
// In the main function, create different routers for each subdomain and pass them to the newSubdomainHandler function | |
func main() { | |
// Create a router for the api domain | |
api := gin.Default() | |
api.GET("/", func(c *gin.Context) { | |
c.String(200, "Welcome to the API") | |
}) | |
// Create a router for the admin subdomain | |
app := gin.Default() | |
app.GET("/", func(c *gin.Context) { | |
c.String(200, "Welcome to the app") | |
}) | |
// Create a map of routers for each subdomain | |
routers := map[string]*gin.Engine{ | |
"api": api, | |
"app": app, | |
} | |
handler := newSubdomainHandler(routers) | |
http.ListenAndServe(":8080", handler) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment