go-pkg/mux/httpmux.go

59 lines
1.4 KiB
Go
Raw Normal View History

2023-07-12 12:43:25 -06:00
package mux
import (
"net/http"
)
type mux struct {
*http.ServeMux
api *http.ServeMux
wellknown *http.ServeMux
2024-01-22 16:00:58 -07:00
handler http.Handler
2023-07-12 12:43:25 -06:00
}
func (mux *mux) Add(fns ...interface{ RegisterHTTP(*http.ServeMux) }) {
for _, fn := range fns {
// log.Printf("HTTP: %T", fn)
fn.RegisterHTTP(mux.ServeMux)
if fn, ok := fn.(interface{ RegisterAPIv1(*http.ServeMux) }); ok {
// log.Printf("APIv1: %T", fn)
fn.RegisterAPIv1(mux.api)
}
if fn, ok := fn.(interface{ RegisterWellKnown(*http.ServeMux) }); ok {
// log.Printf("WellKnown: %T", fn)
fn.RegisterWellKnown(mux.wellknown)
}
2024-01-22 16:00:58 -07:00
if fn, ok := fn.(interface{ RegisterMiddleware(http.Handler) http.Handler }); ok {
hdlr := mux.handler
// log.Printf("WellKnown: %T", fn)
mux.handler = fn.RegisterMiddleware(hdlr)
}
2023-07-12 12:43:25 -06:00
}
}
2024-01-22 16:00:58 -07:00
func (mux *mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
mux.handler.ServeHTTP(w, r)
}
2023-07-12 12:43:25 -06:00
func New() *mux {
mux := &mux{
api: http.NewServeMux(),
wellknown: http.NewServeMux(),
ServeMux: http.NewServeMux(),
}
2024-01-22 16:00:58 -07:00
mux.Handle("/v1/", http.StripPrefix("/v1", mux.api))
2023-07-12 12:43:25 -06:00
mux.Handle("/api/v1/", http.StripPrefix("/api/v1", mux.api))
mux.Handle("/.well-known/", http.StripPrefix("/.well-known", mux.wellknown))
2024-01-22 16:00:58 -07:00
mux.handler = mux.ServeMux
2023-07-12 12:43:25 -06:00
return mux
}
type RegisterHTTP func(*http.ServeMux)
func (fn RegisterHTTP) RegisterHTTP(mux *http.ServeMux) { fn(mux) }