Skip to content

Instantly share code, notes, and snippets.

@wudi
Last active February 8, 2023 16:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wudi/eb778531ff83ee1273f58aa7ddb353fe to your computer and use it in GitHub Desktop.
Save wudi/eb778531ff83ee1273f58aa7ddb353fe to your computer and use it in GitHub Desktop.
Dynamic Router for Gin
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
}
@wudi
Copy link
Author

wudi commented Jun 23, 2020

Try curl http://127.0.0.1:8080/users

output: Hello World

After 10s

output: Hello World (new version)

@miyazawatomoka
Copy link

Don't has any concurrency problems?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment