From 545721076b18787cb8e99288fe04866e342c48c8 Mon Sep 17 00:00:00 2001 From: ajatprabha Date: Thu, 30 Sep 2021 23:53:01 +0530 Subject: [PATCH] expose http.Handler and hide mux router --- cmd/asynqmon/main.go | 16 ++++++++-------- router.go => handler.go | 16 ++++++++++------ 2 files changed, 18 insertions(+), 14 deletions(-) rename router.go => handler.go (94%) diff --git a/cmd/asynqmon/main.go b/cmd/asynqmon/main.go index ddfee24..8b9c83f 100644 --- a/cmd/asynqmon/main.go +++ b/cmd/asynqmon/main.go @@ -5,13 +5,13 @@ import ( "embed" "flag" "fmt" + "github.com/gorilla/mux" "log" "net/http" "strings" "time" "github.com/go-redis/redis/v7" - "github.com/gorilla/mux" "github.com/rs/cors" "github.com/hibiken/asynq" @@ -117,23 +117,23 @@ func main() { } defer redisClient.Close() - router := asynqmon.NewRouter(asynqmon.RouterOptions{ + h := asynqmon.NewHandler(asynqmon.HandlerOptions{ Inspector: inspector, Middlewares: []mux.MiddlewareFunc{loggingMiddleware}, RedisClient: redisClient, + StaticContentHandler: asynqmon.NewStaticContentHandler( + staticContents, + "ui-assets", + "index.html", + ), }) - router.PathPrefix("/"). - Handler(asynqmon.NewStaticContentHandler(staticContents, "ui-assets", "index.html")) - c := cors.New(cors.Options{ AllowedMethods: []string{"GET", "POST", "DELETE"}, }) - handler := c.Handler(router) - srv := &http.Server{ - Handler: handler, + Handler: c.Handler(h), Addr: fmt.Sprintf(":%d", flagPort), WriteTimeout: 10 * time.Second, ReadTimeout: 10 * time.Second, diff --git a/router.go b/handler.go similarity index 94% rename from router.go rename to handler.go index 016d03a..575940f 100644 --- a/router.go +++ b/handler.go @@ -3,18 +3,20 @@ package asynqmon import ( "github.com/go-redis/redis/v7" "github.com/gorilla/mux" + "net/http" "github.com/hibiken/asynq" ) -type RouterOptions struct { - RedisClient redis.UniversalClient - Inspector *asynq.Inspector - Middlewares []mux.MiddlewareFunc - BytesStringer BytesStringer +type HandlerOptions struct { + RedisClient redis.UniversalClient + Inspector *asynq.Inspector + Middlewares []mux.MiddlewareFunc + BytesStringer BytesStringer + StaticContentHandler http.Handler } -func NewRouter(opts RouterOptions) *mux.Router { +func NewHandler(opts HandlerOptions) http.Handler { router := mux.NewRouter() inspector := opts.Inspector t := &transformer{bs: defaultBytesStringer} @@ -98,5 +100,7 @@ func NewRouter(opts RouterOptions) *mux.Router { api.HandleFunc("/redis_info", newRedisInfoHandlerFunc(c)).Methods("GET") } + api.Handle("/", opts.StaticContentHandler) + return router }