expose http.Handler and hide mux router

This commit is contained in:
ajatprabha 2021-09-30 23:53:01 +05:30 committed by Ken Hibino
parent 008c1b1b4a
commit 545721076b
2 changed files with 18 additions and 14 deletions

View File

@ -5,13 +5,13 @@ import (
"embed" "embed"
"flag" "flag"
"fmt" "fmt"
"github.com/gorilla/mux"
"log" "log"
"net/http" "net/http"
"strings" "strings"
"time" "time"
"github.com/go-redis/redis/v7" "github.com/go-redis/redis/v7"
"github.com/gorilla/mux"
"github.com/rs/cors" "github.com/rs/cors"
"github.com/hibiken/asynq" "github.com/hibiken/asynq"
@ -117,23 +117,23 @@ func main() {
} }
defer redisClient.Close() defer redisClient.Close()
router := asynqmon.NewRouter(asynqmon.RouterOptions{ h := asynqmon.NewHandler(asynqmon.HandlerOptions{
Inspector: inspector, Inspector: inspector,
Middlewares: []mux.MiddlewareFunc{loggingMiddleware}, Middlewares: []mux.MiddlewareFunc{loggingMiddleware},
RedisClient: redisClient, 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{ c := cors.New(cors.Options{
AllowedMethods: []string{"GET", "POST", "DELETE"}, AllowedMethods: []string{"GET", "POST", "DELETE"},
}) })
handler := c.Handler(router)
srv := &http.Server{ srv := &http.Server{
Handler: handler, Handler: c.Handler(h),
Addr: fmt.Sprintf(":%d", flagPort), Addr: fmt.Sprintf(":%d", flagPort),
WriteTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second,
ReadTimeout: 10 * time.Second, ReadTimeout: 10 * time.Second,

View File

@ -3,18 +3,20 @@ package asynqmon
import ( import (
"github.com/go-redis/redis/v7" "github.com/go-redis/redis/v7"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"net/http"
"github.com/hibiken/asynq" "github.com/hibiken/asynq"
) )
type RouterOptions struct { type HandlerOptions struct {
RedisClient redis.UniversalClient RedisClient redis.UniversalClient
Inspector *asynq.Inspector Inspector *asynq.Inspector
Middlewares []mux.MiddlewareFunc Middlewares []mux.MiddlewareFunc
BytesStringer BytesStringer BytesStringer BytesStringer
StaticContentHandler http.Handler
} }
func NewRouter(opts RouterOptions) *mux.Router { func NewHandler(opts HandlerOptions) http.Handler {
router := mux.NewRouter() router := mux.NewRouter()
inspector := opts.Inspector inspector := opts.Inspector
t := &transformer{bs: defaultBytesStringer} t := &transformer{bs: defaultBytesStringer}
@ -98,5 +100,7 @@ func NewRouter(opts RouterOptions) *mux.Router {
api.HandleFunc("/redis_info", newRedisInfoHandlerFunc(c)).Methods("GET") api.HandleFunc("/redis_info", newRedisInfoHandlerFunc(c)).Methods("GET")
} }
api.Handle("/", opts.StaticContentHandler)
return router return router
} }