refactor: push commands in to cmd and ev to root as library
This commit is contained in:
45
pkg/mux/httpmux.go
Normal file
45
pkg/mux/httpmux.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type mux struct {
|
||||
*http.ServeMux
|
||||
api *http.ServeMux
|
||||
wellknown *http.ServeMux
|
||||
}
|
||||
|
||||
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("APIv1: %T", fn)
|
||||
fn.RegisterWellKnown(mux.wellknown)
|
||||
}
|
||||
}
|
||||
}
|
||||
func New() *mux {
|
||||
mux := &mux{
|
||||
api: http.NewServeMux(),
|
||||
wellknown: http.NewServeMux(),
|
||||
ServeMux: http.NewServeMux(),
|
||||
}
|
||||
mux.Handle("/api/v1/", http.StripPrefix("/api/v1", mux.api))
|
||||
mux.Handle("/.well-known/", http.StripPrefix("/.well-known/", mux.api))
|
||||
|
||||
return mux
|
||||
}
|
||||
|
||||
type RegisterHTTP func(*http.ServeMux)
|
||||
|
||||
func (fn RegisterHTTP) RegisterHTTP(mux *http.ServeMux) {
|
||||
fn(mux)
|
||||
}
|
||||
41
pkg/mux/httpmux_test.go
Normal file
41
pkg/mux/httpmux_test.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package mux_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/matryer/is"
|
||||
"github.com/sour-is/ev/pkg/mux"
|
||||
)
|
||||
|
||||
type mockHTTP struct {
|
||||
onServeHTTP func()
|
||||
}
|
||||
|
||||
func (m *mockHTTP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
m.onServeHTTP()
|
||||
}
|
||||
func (h *mockHTTP) RegisterHTTP(mux *http.ServeMux) {
|
||||
mux.Handle("/", h)
|
||||
}
|
||||
func (h *mockHTTP) RegisterAPIv1(mux *http.ServeMux) {
|
||||
mux.Handle("/ping", h)
|
||||
}
|
||||
|
||||
func TestHttpMux(t *testing.T) {
|
||||
is := is.New(t)
|
||||
|
||||
called := false
|
||||
|
||||
mux := mux.New()
|
||||
mux.Add(&mockHTTP{func() { called = true }})
|
||||
|
||||
is.True(mux != nil)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
r := httptest.NewRequest(http.MethodGet, "/api/v1/ping", nil)
|
||||
mux.ServeHTTP(w, r)
|
||||
|
||||
is.True(called)
|
||||
}
|
||||
Reference in New Issue
Block a user