Skip to content

Commit

Permalink
feat(serve-http): add ServeHTTP func for server
Browse files Browse the repository at this point in the history
  • Loading branch information
pkkummermo committed Sep 28, 2024
1 parent 8c24c5b commit 292aaba
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
30 changes: 30 additions & 0 deletions serve-http.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
59 changes: 59 additions & 0 deletions serve-http_test.go
Original file line number Diff line number Diff line change
@@ -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",
)
})
}

0 comments on commit 292aaba

Please sign in to comment.