70 lines
1.8 KiB
Go
70 lines
1.8 KiB
Go
package omni
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"git.yuntuo.hk/k2safe/go-omni/httpx"
|
|
)
|
|
|
|
func TestNewWithRouterKeepsHandlersTransportNeutral(t *testing.T) {
|
|
router := &testRouter{}
|
|
app := NewWithRouter(router)
|
|
app.GET("/health", func(ctx *Context) error {
|
|
if ctx.RequestID() == "" {
|
|
t.Fatal("expected request ID from core middleware")
|
|
}
|
|
return ctx.OK(map[string]string{"status": "ok"})
|
|
})
|
|
|
|
recorder := httptest.NewRecorder()
|
|
request := httptest.NewRequest(http.MethodGet, "/health", nil)
|
|
app.ServeHTTP(recorder, request)
|
|
if recorder.Code != http.StatusOK {
|
|
t.Fatalf("expected status 200, got %d", recorder.Code)
|
|
}
|
|
}
|
|
|
|
type testRouter struct {
|
|
handlers map[string]http.Handler
|
|
}
|
|
|
|
func (r *testRouter) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
|
if handler := r.handlers[request.Method+" "+request.URL.Path]; handler != nil {
|
|
handler.ServeHTTP(writer, request)
|
|
return
|
|
}
|
|
http.NotFound(writer, request)
|
|
}
|
|
|
|
func (r *testRouter) Handle(method, path string, handler http.Handler) {
|
|
if r.handlers == nil {
|
|
r.handlers = make(map[string]http.Handler)
|
|
}
|
|
r.handlers[method+" "+path] = handler
|
|
}
|
|
|
|
func (r *testRouter) Any(path string, handler http.Handler) { r.Handle(http.MethodGet, path, handler) }
|
|
|
|
func (r *testRouter) Group(path string) httpx.RouterGroup {
|
|
return &testRouterGroup{router: r, prefix: path}
|
|
}
|
|
|
|
type testRouterGroup struct {
|
|
router *testRouter
|
|
prefix string
|
|
}
|
|
|
|
func (g *testRouterGroup) Handle(method, path string, handler http.Handler) {
|
|
g.router.Handle(method, g.prefix+path, handler)
|
|
}
|
|
|
|
func (g *testRouterGroup) Any(path string, handler http.Handler) {
|
|
g.Handle(http.MethodGet, path, handler)
|
|
}
|
|
|
|
func (g *testRouterGroup) Group(path string) httpx.RouterGroup {
|
|
return &testRouterGroup{router: g.router, prefix: g.prefix + path}
|
|
}
|