Skip to content
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
5 changes: 5 additions & 0 deletions binder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,8 @@
*/

package okapi

import "testing"

func TestContext_Bind(t *testing.T) {
}
71 changes: 68 additions & 3 deletions group.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@

package okapi

import "net/http"

type Group struct {
basePath string
disabled bool
Expand Down Expand Up @@ -151,8 +153,71 @@ func (g *Group) Trace(path string, h HandleFunc, opts ...RouteOption) *Route {
// The new group inherits all middlewares from its parent group.
func (g *Group) Group(path string, middlewares ...Middleware) *Group {
return newGroup(
joinPaths(g.basePath, path), // Combine paths
// Combine paths
joinPaths(g.basePath, path),
g.disabled,
g.okapi, // Share the same Okapi instance
append(g.middlewares, middlewares...)...) // Combine middlewares
// Share the same Okapi instance
g.okapi,
// Combine middlewares
append(g.middlewares, middlewares...)...)
}

// HandleStd registers a standard http.HandlerFunc and wraps it with the group's middleware chain.
func (g *Group) HandleStd(method, path string, h func(http.ResponseWriter, *http.Request), opts ...RouteOption) {
// Convert standard handler to HandleFunc
converted := func(c Context) error {
h(c.Response, c.Request)
return nil
}
// Apply group middleware
for i := len(g.middlewares) - 1; i >= 0; i-- {
converted = g.middlewares[i](converted)
}
// Register route
g.okapi.addRoute(method, joinPaths(g.basePath, path), g.basePath, converted, opts...).SetDisabled(g.disabled)
}

// HandleHTTP registers a standard http.Handler and wraps it with the group's middleware chain.
func (g *Group) HandleHTTP(method, path string, h http.HandlerFunc, opts ...RouteOption) {
// Convert standard handler to HandleFunc
converted := func(c Context) error {
h.ServeHTTP(c.Response, c.Request)
return nil
}
// Apply group middleware
for i := len(g.middlewares) - 1; i >= 0; i-- {
converted = g.middlewares[i](converted)
}
// Register route
g.okapi.addRoute(method, joinPaths(g.basePath, path), g.basePath, converted, opts...).SetDisabled(g.disabled)
}

// UseMiddleware registers a standard HTTP middleware function and integrates
// it into Okapi's middleware chain.
//
// This enables compatibility with existing middleware libraries that use the
// func(http.Handler) http.Handler pattern.
func (g *Group) UseMiddleware(mw func(http.Handler) http.Handler) {
g.Use(func(next HandleFunc) HandleFunc {
// Convert HandleFunc to http.Handler
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := Context{
Request: r,
Response: &response{writer: w},
okapi: g.okapi,
}
if err := next(ctx); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})

// Apply standard middleware
wrapped := mw(h)

// Convert back to HandleFunc
return func(ctx Context) error {
wrapped.ServeHTTP(ctx.Response, ctx.Request)
return nil
}
})
}
73 changes: 73 additions & 0 deletions groupe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,76 @@
*/

package okapi

import (
"errors"
"log/slog"
"net/http"
"testing"
)

func TestGroup(t *testing.T) {
o := Default()
// create api group
api := o.Group("/api")
// Okapi's Group Middleware
api.Use(func(next HandleFunc) HandleFunc {
return func(c Context) (err error) {
slog.Info("Okapi's Group middleware")
return next(c)
}
})
// Go's standard HTTP middleware function
api.UseMiddleware(func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
slog.Info("Hello Go standard HTTP middleware function")
handler.ServeHTTP(w, r)
})

})
// Go's standard http.HandlerFunc
api.HandleStd("GET", "/standard", func(w http.ResponseWriter, r *http.Request) {
slog.Info("Calling route", "path", r.URL.Path)
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("standard standard http.HandlerFunc response"))
if err != nil {
return
}
})
// Okapi Group HandleFun
api.Get("hello", helloHandler)
api.Post("hello", helloHandler)
api.Put("hello", helloHandler)
api.Patch("hello", helloHandler)
api.Delete("hello", helloHandler)
api.Options("hello", helloHandler)

api.Get("/group", func(c Context) error {
slog.Info("Calling route", "path", c.Request.URL.Path)
return c.OK(M{"message": "Welcome to Okapi!"})
})

go func() {
if err := o.Start(); err != nil && !errors.Is(err, http.ErrServerClosed) {
t.Errorf("Server failed to start: %v", err)
}
}()
defer o.Stop()

waitForServer()

assertStatus(t, "GET", "http://localhost:8080/api/group", nil, "", http.StatusOK)
assertStatus(t, "GET", "http://localhost:8080/api/standard", nil, "", http.StatusOK)

assertStatus(t, "GET", "http://localhost:8080/api/hello", nil, "", http.StatusOK)
assertStatus(t, "POST", "http://localhost:8080/api/hello", nil, "", http.StatusOK)
assertStatus(t, "PUT", "http://localhost:8080/api/hello", nil, "", http.StatusOK)
assertStatus(t, "PATCH", "http://localhost:8080/api/hello", nil, "", http.StatusOK)
assertStatus(t, "DELETE", "http://localhost:8080/api/hello", nil, "", http.StatusOK)
assertStatus(t, "OPTIONS", "http://localhost:8080/api/hello", nil, "", http.StatusOK)
}
func helloHandler(c Context) error {
slog.Info("Calling route", "path", c.Request.URL.Path, "method", c.Request.Method)
return c.OK(M{"message": "Hello from Okapi!"})

}
21 changes: 19 additions & 2 deletions okapi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,12 @@ func TestStart(t *testing.T) {
o.Get("/", func(c Context) error {
return c.OK(M{"message": "Welcome to Okapi!"})
})

o.Get("hello", helloHandler)
o.Post("hello", helloHandler)
o.Put("hello", helloHandler)
o.Patch("hello", helloHandler)
o.Delete("hello", helloHandler)
o.Options("hello", helloHandler)
basicAuth := BasicAuthMiddleware{
Username: "admin",
Password: "password",
Expand All @@ -68,7 +73,12 @@ func TestStart(t *testing.T) {
api := o.Group("/api")
adminApi := api.Group("/admin", basicAuth.Middleware)
adminApi.Put("/books/:id", adminUpdate)
adminApi.Post("/books", adminStore)
adminApi.Post("/books", adminStore,
DocSummary("Book Summary"),
DocResponse(Book{}),
DocRequestBody(Book{}),
DocTags("Book Tag"),
)

v1 := api.Group("/v1")
v1.Use(customMiddleware)
Expand Down Expand Up @@ -107,6 +117,13 @@ func TestStart(t *testing.T) {
assertStatus(t, "GET", "http://localhost:8080/api/v1/any/request", nil, "", http.StatusOK)
assertStatus(t, "GET", "http://localhost:8080/api/v1/all/request", nil, "", http.StatusOK)

assertStatus(t, "GET", "http://localhost:8080/hello", nil, "", http.StatusOK)
assertStatus(t, "POST", "http://localhost:8080/hello", nil, "", http.StatusOK)
assertStatus(t, "PUT", "http://localhost:8080/hello", nil, "", http.StatusOK)
assertStatus(t, "PATCH", "http://localhost:8080/hello", nil, "", http.StatusOK)
assertStatus(t, "DELETE", "http://localhost:8080/hello", nil, "", http.StatusOK)
assertStatus(t, "OPTIONS", "http://localhost:8080/hello", nil, "", http.StatusOK)

// Unauthorized admin Post
body := `{"id":5,"name":"The Go Programming Language","price":30,"qty":100}`
assertStatus(t, "POST",
Expand Down
130 changes: 130 additions & 0 deletions openapi_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
* MIT License
*
* Copyright (c) 2025 Jonas Kaninda
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package okapi

import (
"errors"
"log/slog"
"net/http"
"testing"
)

func TestOpenAPI(t *testing.T) {
o := Default()
// create api group
api := o.Group("api")
v1 := api.Group("v1")
v2 := api.Group("v2")
v1.Post("/books", anyHandler,
DocSummary("Book Summary"),
DocAutoPathParams(),
DocQueryParam("auth", "string", "auth name", true),
DocBearerAuth(),
DocResponse(Book{}),
DocRequestBody(Book{}),
DocTags("Book Tag"),
DocErrorResponse(http.StatusBadRequest, M{"": ""}),
)
v1.Put("/books", anyHandler,
DocSummary("Book Summary"),
DocAutoPathParams(),
DocQueryParam("auth", "string", "auth name", true),
DocBearerAuth(),
DocResponse(Book{}),
DocRequestBody(Book{}),
DocTags("Book Tag"),
DocErrorResponse(http.StatusBadRequest, M{"": ""}),
)
v1.Get("/books", anyHandler,
DocSummary("Books Summary"),
DocQueryParam("auth", "string", "auth name", true),
DocResponse(Book{}),
DocRequestBody(Book{}),
DocTags("Book Tag"),
DocErrorResponse(http.StatusBadRequest, M{"": ""}),
DocDeprecated(),
)
v1.Delete("/books/{id}", anyHandler,
DocSummary("Book Summary"),
DocPathParam("id", "int", "book id"),
DocResponse(Book{}),
DocRequestBody(Book{}),
DocTags("Book Tag"),
DocErrorResponse(http.StatusBadRequest, M{"": ""}),
DocDeprecated(),
)
// V2
v2.Post("/books", anyHandler,
DocSummary("Book Summary"),
DocAutoPathParams(),
DocQueryParam("auth", "string", "auth name", true),
DocBearerAuth(),
DocResponse(Book{}),
DocRequestBody(Book{}),
DocTags("Book Tag"),
DocErrorResponse(http.StatusBadRequest, M{"": ""}),
)
v2.Put("/books", anyHandler,
Doc().Summary("Book Summary").
BearerAuth().
Response(Book{}).
RequestBody(Book{}).
Tags("Book Tag").
ErrorResponse(http.StatusBadRequest, M{"": ""}).AsOption(),
)
v2.Get("/books", anyHandler,
Doc().Summary("Book Summary").
BearerAuth().
QueryParam("auth", "string", "auth name", true).
Response(Book{}).
Tags("Book Tag").
ErrorResponse(http.StatusBadRequest, M{"": ""}).Build(),
)
v2.Delete("/books/:id", anyHandler,
Doc().Summary("Delete Book").
BearerAuth().
PathParam("id", "int", "book id").
Response(Book{}).
Tags("Book Tag").
ErrorResponse(http.StatusBadRequest, M{"": ""}).Build(),
)
go func() {
if err := o.Start(); err != nil && !errors.Is(err, http.ErrServerClosed) {
t.Errorf("Server failed to start: %v", err)
}
}()
defer o.Stop()

waitForServer()

assertStatus(t, "GET", "http://localhost:8080/docs", nil, "", http.StatusOK)
assertStatus(t, "GET", "http://localhost:8080/openapi.json", nil, "", http.StatusOK)

}
func anyHandler(c Context) error {
slog.Info("Calling route", "path", c.Request.URL.Path, "method", c.Request.Method)
return c.OK(M{"message": "Hello from Okapi!"})

}