Last active
February 8, 2023 16:53
-
-
Save wudi/eb778531ff83ee1273f58aa7ddb353fe to your computer and use it in GitHub Desktop.
Dynamic Router for Gin
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" | |
"sync" | |
"time" | |
"github.com/gin-gonic/gin" | |
) | |
type dynamicRouter struct { | |
h http.Handler | |
mu sync.Mutex | |
} | |
func main() { | |
http.ListenAndServe(":8080", newDynamicRouter()) | |
} | |
func newDynamicRouter() http.Handler { | |
dr := &dynamicRouter{} | |
e := gin.New() | |
// Default routes | |
e.GET("/users", func(ctx *gin.Context) { | |
ctx.String(200, "Hello World") | |
}) | |
dr.h = e | |
go func() { | |
// Change routes dynamic | |
time.AfterFunc(10*time.Second, func() { | |
// Build new handler exclude somes that u want. | |
var newHandler = gin.New() | |
newHandler.GET("/users", func(ctx *gin.Context) { | |
ctx.String(200, "Hello World (new version)") | |
}) | |
// TODO: try another way more secure | |
dr.h = newHandler | |
}) | |
}() | |
return dr | |
} | |
func (dt *dynamicRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
dt.h.ServeHTTP(w, r) | |
} | |
func (dt *dynamicRouter) SetHandler(h http.Handler) { | |
dt.mu.Lock() | |
defer dt.mu.Unlock() | |
dt.h = h | |
} |
Don't has any concurrency problems?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try
curl http://127.0.0.1:8080/users
output:
Hello World
After 10s
output:
Hello World (new version)