Skip to content

feat: make kid configurable #36

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

Merged
merged 1 commit into from
Mar 15, 2023
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
38 changes: 30 additions & 8 deletions kid.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package kid
import (
"net/http"
"net/url"
"reflect"
"sync"

htmlrenderer "github.com/mojixcoder/kid/html_renderer"
Expand Down Expand Up @@ -69,9 +70,7 @@ func (k *Kid) Run(address ...string) error {

// Use registers a new middleware. The middleware will be applied to all of the routes.
func (k *Kid) Use(middleware MiddlewareFunc) {
if middleware == nil {
panic("middleware cannot be nil")
}
panicIfNil(middleware, "middleware cannot be nil")

k.middlewares = append(k.middlewares, middleware)
}
Expand Down Expand Up @@ -209,11 +208,6 @@ func (k *Kid) ServeHTTP(w http.ResponseWriter, r *http.Request) {
k.pool.Put(c)
}

// Debug returns whether we are in debug mode or not.
func (k *Kid) Debug() bool {
return k.debug
}

// applyMiddlewaresToHandler applies middlewares to the handler and returns the handler.
func (k *Kid) applyMiddlewaresToHandler(handler HandlerFunc, middlewares ...MiddlewareFunc) HandlerFunc {
for i := len(middlewares) - 1; i >= 0; i-- {
Expand All @@ -222,6 +216,20 @@ func (k *Kid) applyMiddlewaresToHandler(handler HandlerFunc, middlewares ...Midd
return handler
}

// Debug returns whether we are in debug mode or not.
func (k *Kid) Debug() bool {
return k.debug
}

// ApplyOptions applies the given options.
func (k *Kid) ApplyOptions(opts ...Option) {
for _, opt := range opts {
panicIfNil(opt, "option cannot be nil")

opt.apply(k)
}
}

// getPath returns request's path.
func getPath(u *url.URL) string {
if u.RawPath != "" {
Expand All @@ -237,3 +245,17 @@ func resolveAddress(addresses []string) string {
}
return addresses[0]
}

// panicIfNil panics if the given parameter is nil.
func panicIfNil(x any, message string) {
if x == nil {
panic(message)
}

switch reflect.TypeOf(x).Kind() {
case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice, reflect.Interface, reflect.Func:
if reflect.ValueOf(x).IsNil() {
panic(message)
}
}
}
60 changes: 60 additions & 0 deletions kid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -623,3 +623,63 @@ func TestGetPath(t *testing.T) {
assert.NotEmpty(t, u.RawPath)
assert.Equal(t, u.RawPath, getPath(u))
}

func TestApplyOptions(t *testing.T) {
k := New()

assert.PanicsWithValue(t, "option cannot be nil", func() {
k.ApplyOptions(nil)
})

handler := func(c *Context, err error) {
}

k.ApplyOptions(
WithDebug(true),
WithErrorHandler(handler),
)

assert.True(t, k.Debug())
assert.True(t, funcsAreEqual(handler, k.errorHandler))
}

func TestPanicIfNil(t *testing.T) {
assert.PanicsWithValue(t, "nil", func() {
panicIfNil(nil, "nil")
})

assert.Panics(t, func() {
var x *int
panicIfNil(x, "")
})

assert.Panics(t, func() {
var x []string
panicIfNil(x, "")
})

assert.Panics(t, func() {
var x map[string]string
panicIfNil(x, "")
})

assert.Panics(t, func() {
var x interface{}
panicIfNil(x, "")
})

assert.Panics(t, func() {
var x func()
panicIfNil(x, "")
})

assert.Panics(t, func() {
var x chan bool
panicIfNil(x, "")
})

assert.Panics(t, func() {
var x [1]int
panicIfNil(x, "")
})
}
4 changes: 1 addition & 3 deletions mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ func (router *Router) add(path string, handler HandlerFunc, methods []string, mi
panic("providing at least one method is required")
}

if handler == nil {
panic("handler cannot be nil")
}
panicIfNil(handler, "handler cannot be nil")

path = cleanPath(path, false)

Expand Down
81 changes: 81 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package kid

import (
htmlrenderer "github.com/mojixcoder/kid/html_renderer"
"github.com/mojixcoder/kid/serializer"
)

type (
// Option is the interface for customizing Kid.
Option interface {
apply(*Kid)
}

optionImpl func(*Kid)
)

// applyOption implements the Option interface.
func (f optionImpl) apply(k *Kid) {
f(k)
}

// WithDebug configures Kid's debug option.
func WithDebug(debug bool) Option {
return optionImpl(func(k *Kid) {
k.debug = debug
})
}

// WithHTMLRenderer configures Kid's HTML renderer.
func WithHTMLRenderer(renderer htmlrenderer.HTMLRenderer) Option {
panicIfNil(renderer, "renderer cannot be nil")

return optionImpl(func(k *Kid) {
k.htmlRenderer = renderer
})
}

// WithXMLSerializer configures Kid's XML serializer.
func WithXMLSerializer(serializer serializer.Serializer) Option {
panicIfNil(serializer, "xml serializer cannot be nil")

return optionImpl(func(k *Kid) {
k.xmlSerializer = serializer
})
}

// WithJSONSerializer configures Kid's JSON serializer.
func WithJSONSerializer(serializer serializer.Serializer) Option {
panicIfNil(serializer, "json serializer cannot be nil")

return optionImpl(func(k *Kid) {
k.jsonSerializer = serializer
})
}

// WithErrorHandler configures Kid's error handler.
func WithErrorHandler(errHandler ErrorHandler) Option {
panicIfNil(errHandler, "error handler cannot be nil")

return optionImpl(func(k *Kid) {
k.errorHandler = errHandler
})
}

// WithNotFoundHandler configures Kid's not found handler.
func WithNotFoundHandler(handler HandlerFunc) Option {
panicIfNil(handler, "not found handler cannot be nil")

return optionImpl(func(k *Kid) {
k.notFoundHandler = handler
})
}

// WithMethodNotAllowedHandler configures Kid's method not allowed handler.
func WithMethodNotAllowedHandler(handler HandlerFunc) Option {
panicIfNil(handler, "method not allowed handler cannot be nil")

return optionImpl(func(k *Kid) {
k.methodNotAllowedHandler = handler
})
}
126 changes: 126 additions & 0 deletions options_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package kid

import (
"net/http"
"testing"

"github.com/stretchr/testify/assert"
)

type mockEverything struct{}

func (*mockEverything) RenderHTML(res http.ResponseWriter, path string, data any) error {
return nil
}

func (*mockEverything) Write(w http.ResponseWriter, in any, indent string) error {
return nil
}

func (*mockEverything) Read(req *http.Request, out any) error {
return nil
}

func TestWithDebug(t *testing.T) {
k := New()

opt := WithDebug(true)
opt.apply(k)

assert.True(t, k.Debug())
}

func TestWithHTMLRenderer(t *testing.T) {
k := New()

assert.PanicsWithValue(t, "renderer cannot be nil", func() {
WithHTMLRenderer(nil)
})

renderer := &mockEverything{}

opt := WithHTMLRenderer(renderer)
opt.apply(k)

assert.Equal(t, renderer, k.htmlRenderer)
}

func TestWithXMLSerializer(t *testing.T) {
k := New()

assert.PanicsWithValue(t, "xml serializer cannot be nil", func() {
WithXMLSerializer(nil)
})

serializer := &mockEverything{}

opt := WithXMLSerializer(serializer)
opt.apply(k)

assert.Equal(t, serializer, k.xmlSerializer)
}

func TestWithJSONSerializer(t *testing.T) {
k := New()

assert.PanicsWithValue(t, "json serializer cannot be nil", func() {
WithJSONSerializer(nil)
})

serializer := &mockEverything{}

opt := WithJSONSerializer(serializer)
opt.apply(k)

assert.Equal(t, serializer, k.jsonSerializer)
}

func TestWithErrorHandler(t *testing.T) {
k := New()

assert.PanicsWithValue(t, "error handler cannot be nil", func() {
WithErrorHandler(nil)
})

hanlder := func(c *Context, err error) {
}

opt := WithErrorHandler(hanlder)
opt.apply(k)

assert.True(t, funcsAreEqual(hanlder, k.errorHandler))
}

func TestWithNotFoundHandler(t *testing.T) {
k := New()

assert.PanicsWithValue(t, "not found handler cannot be nil", func() {
WithNotFoundHandler(nil)
})

hanlder := func(c *Context) error {
return nil
}

opt := WithNotFoundHandler(hanlder)
opt.apply(k)

assert.True(t, funcsAreEqual(hanlder, k.notFoundHandler))
}

func TestWithMethodNotAllowedHandler(t *testing.T) {
k := New()

assert.PanicsWithValue(t, "method not allowed handler cannot be nil", func() {
WithMethodNotAllowedHandler(nil)
})

hanlder := func(c *Context) error {
return nil
}

opt := WithMethodNotAllowedHandler(hanlder)
opt.apply(k)

assert.True(t, funcsAreEqual(hanlder, k.methodNotAllowedHandler))
}
4 changes: 1 addition & 3 deletions static.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ func (fs FS) Open(name string) (http.File, error) {

// newFileServer returns new file server.
func newFileServer(urlPath string, fs http.FileSystem) http.Handler {
if fs == nil {
panic("file system cannot be nil")
}
panicIfNil(fs, "file system cannot be nil")

urlPath = cleanPath(urlPath, false)
urlPath = appendSlash(urlPath)
Expand Down