diff --git a/serve-http.go b/serve-http.go new file mode 100644 index 0000000..e725350 --- /dev/null +++ b/serve-http.go @@ -0,0 +1,30 @@ +package govalin + +import ( + "net/http" +) + +type ServeHTTPFunc func(w http.ResponseWriter, r *http.Request) + +// HttpServe registers a ServeHttpFunc to a path which adheres to the http.Handler interface. +func (server *App) HTTPServe(path string, httpServeFunc ServeHTTPFunc) { + fullPath := server.currentFragment + path + handler := server.getOrCreatePathHandlerByPath(fullPath) + + handlerFunc := func(call *Call) { + call.bypassLifecycle = true + httpServeFunc(*call.Raw.W, call.Raw.Req) + } + + handler.Get = handlerFunc + handler.Post = handlerFunc + handler.Put = handlerFunc + handler.Patch = handlerFunc + handler.Delete = handlerFunc + handler.Options = handlerFunc + handler.Head = handlerFunc + + for _, onRouteAdded := range server.config.server.events.onRouteAdded { + onRouteAdded("ServeHTTP", fullPath, handlerFunc) + } +} diff --git a/serve-http_test.go b/serve-http_test.go new file mode 100644 index 0000000..7dea1b5 --- /dev/null +++ b/serve-http_test.go @@ -0,0 +1,59 @@ +package govalin_test + +import ( + "net/http" + "testing" + + "github.com/pkkummermo/govalin" + "github.com/pkkummermo/govalin/internal/govalintesting" + "github.com/stretchr/testify/assert" +) + +func TestServeHTTP(t *testing.T) { + govalintesting.HTTPTestUtil(func(app *govalin.App) *govalin.App { + app.HTTPServe("/httpserve", func(w http.ResponseWriter, _ *http.Request) { + _, err := w.Write([]byte("httpservegovalin")) + w.WriteHeader(http.StatusOK) + assert.Nil(t, err, "Should write to response writer") + }) + + return app + }, func(http govalintesting.GovalinHTTP) { + assert.Equal( + t, + "httpservegovalin", + http.Get("/httpserve", nil), + "Should create httpserve GET endpoint", + ) + assert.Equal( + t, + "httpservegovalin", + http.Post("/httpserve", nil), + "Should create httpserve POST endpoint", + ) + assert.Equal( + t, + "httpservegovalin", + http.Patch("/httpserve", nil), + "Should create httpserve PATCH endpoint", + ) + assert.Equal( + t, + "httpservegovalin", + http.Delete("/httpserve", nil), + "Should create httpserve DELETE endpoint", + ) + assert.Equal( + t, + "httpservegovalin", + http.Options("/httpserve", nil), + "Should create httpserve OPTIONS endpoint", + ) + assert.Equal( + t, + "", + http.Head("/httpserve"), + "Should create httpserve HEAD endpoint", + ) + }) +}