Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(serve-http): add ServeHTTP func for server #49

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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",
)
})
}
Loading