kid

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 1, 2024 License: MIT Imports: 16 Imported by: 0

README

test code quality coverage

Kid Micro Web Framework


Kid is a micro web framework written in Go. It aims to keep its core simple and yet powerful. It's fully compatible with net/http interfaces and can be adapted with other net/http compatible packages as well.

Features


  • Robust tree-based router.
  • Path parameters.
  • Router groups.
  • Rich built-in responses(JSON, HTML, XML, string, byte).
  • Middlewares.
  • Zero dependency, only standard library.
  • Compatible with net/http interfaces.
  • Extendable, you can also use your own JSON, XML serializers or HTML renderer.

Versioning


This package follows semver versioning.

Quick Start


To install Kid Go 1.19 or higher is required: go get github.com/mojixcoder/kid

Create server.go:

package main

import (
    "net/http"

    "github.com/mojixcoder/kid"
)

func main() {
    k := kid.New()

    k.Get("/hello", helloHandler)

    k.Run()
}

func helloHandler(c *kid.Context) {
    c.JSON(http.StatusOK, kid.Map{"message": "Hello Kid!"})
}

Documentation

Index

Constants

View Source
const Version string = "v0.4.0"

Version of Kid.

Variables

This section is empty.

Functions

This section is empty.

Types

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context is the context of current HTTP request. It holds data related to current HTTP request.

func (*Context) Byte

func (c *Context) Byte(code int, data []byte)

Byte sends bare bytes as response with the given status code.

func (*Context) Clone added in v0.3.0

func (c *Context) Clone() *Context

Clone clones the context and returns it.

Should be used when context is passed to the background jobs.

Writes to the response of a cloned context will panic.

func (*Context) Debug

func (c *Context) Debug() bool

Debug returns whether we are in debug mode or not.

func (*Context) Get

func (c *Context) Get(key string) (any, bool)

Get gets a value from current request's context.

func (*Context) GetRequestHeader

func (c *Context) GetRequestHeader(key string) string

GetRequestHeader gets a request header.

func (*Context) GetResponseHeader

func (c *Context) GetResponseHeader(key string) string

GetResponseHeader gets a response header.

func (*Context) HTML

func (c *Context) HTML(code int, tpl string, data any)

HTML sends HTML response with the given status code.

tpl must be a relative path to templates root directory. Defaults to "templates/".

func (*Context) HTMLString

func (c *Context) HTMLString(code int, tpl string)

HTMLString sends bare string as HTML response with the given status code.

func (*Context) JSON

func (c *Context) JSON(code int, obj any)

JSON sends JSON response with the given status code.

func (*Context) JSONByte

func (c *Context) JSONByte(code int, blob []byte)

JSONByte sends JSON response with the given status code. Writes JSON blob untouched to response.

func (*Context) JSONIndent

func (c *Context) JSONIndent(code int, obj any, indent string)

JSONIndent sends JSON response with the given status code. Sends response with the given indent.

func (*Context) Method added in v0.3.0

func (c *Context) Method() string

Method returns request method.

func (*Context) NoContent

func (c *Context) NoContent(code int)

NoContent returns an empty response with the given status code.

func (*Context) Param

func (c *Context) Param(name string) string

Param returns path parameter's value.

func (*Context) Params

func (c *Context) Params() Params

Params returns all of the path parameters.

func (*Context) Path added in v0.3.0

func (c *Context) Path() string

Path returns request's path used for matching request to a handler.

func (*Context) QueryParam

func (c *Context) QueryParam(name string) string

QueryParam returns value of a query parameter

func (*Context) QueryParamMultiple

func (c *Context) QueryParamMultiple(name string) []string

QueryParamMultiple returns multiple values of a query parameter.

Useful when query parameters are like ?name=x&name=y.

func (*Context) QueryParams

func (c *Context) QueryParams() url.Values

QueryParams returns all of the query parameters.

func (*Context) ReadJSON

func (c *Context) ReadJSON(out any) error

ReadJSON reads request's body as JSON and stores it in the given object. The object must be a pointer.

func (*Context) ReadXML

func (c *Context) ReadXML(out any) error

ReadXML reads request's body as XML and stores it in the given object. The object must be a pointer.

func (*Context) Request

func (c *Context) Request() *http.Request

Request returns plain request of current HTTP request.

func (*Context) Response

func (c *Context) Response() ResponseWriter

Response returns plain response of current HTTP request.

func (*Context) Route added in v0.4.0

func (c *Context) Route() string

Route returns current request's route name. It's the user entered path, e.g. /greet/{name}.

func (*Context) Set

func (c *Context) Set(key string, val any)

Set sets a key-value pair to current request's context.

func (*Context) SetRequestHeader

func (c *Context) SetRequestHeader(key, value string)

SetRequestHeader sets a header to the request.

func (*Context) SetResponseHeader

func (c *Context) SetResponseHeader(key, value string)

SetResponseHeader sets a header to the response.

func (*Context) String

func (c *Context) String(code int, data string)

String sends bare string as a plain text response with the given status code.

func (*Context) XML

func (c *Context) XML(code int, obj any)

XML sends XML response with the given status code.

Returns an error if an error happened during sending response otherwise returns nil.

func (*Context) XMLByte

func (c *Context) XMLByte(code int, blob []byte)

XMLByte sends XML response with the given status code. Writes JSON blob untouched to response.

func (*Context) XMLIndent

func (c *Context) XMLIndent(code int, obj any, indent string)

XMLIndent sends XML response with the given status code. Sends response with the given indent.

type FS

type FS struct {
	http.FileSystem
}

FS is Kid's http.FileSystem implementation to disable directory listing.

func (FS) Open

func (fs FS) Open(name string) (http.File, error)

Open overrides http.FileSystem's default implementation to disable directory listing.

type File

type File struct {
	http.File
}

File is Kid's http.File implementation to disable directory listing.

func (File) Readdir

func (f File) Readdir(count int) ([]os.FileInfo, error)

Readdir overrides http.File's default implementation.

It disables directory listing.

type Group

type Group struct {
	// contains filtered or unexported fields
}

Group is for creating groups of routes.

It doesn't actually group them but it's kind of an abstraction to make it easier to make a group of routes.

func (*Group) Add

func (g *Group) Add(path string, handler HandlerFunc, methods []string, middlewares ...MiddlewareFunc)

Add adds a route to the group routes.

func (*Group) Any

func (g *Group) Any(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Any registers a new handler for the given path for all of the HTTP methods.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Group) Connect

func (g *Group) Connect(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Connect registers a new handler for the given path for CONNECT method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Group) Delete

func (g *Group) Delete(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Delete registers a new handler for the given path for DELETE method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Group) Get

func (g *Group) Get(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Get registers a new handler for the given path for GET method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Group) Group

func (g *Group) Group(prefix string, middlewares ...MiddlewareFunc) Group

Group creates a sub-group for that group.

func (*Group) Head

func (g *Group) Head(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Head registers a new handler for the given path for HEAD method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Group) Options

func (g *Group) Options(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Options registers a new handler for the given path for OPTIONS method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Group) Patch

func (g *Group) Patch(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Patch registers a new handler for the given path for PATCH method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Group) Post

func (g *Group) Post(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Post registers a new handler for the given path for POST method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Group) Put

func (g *Group) Put(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Put registers a new handler for the given path for PUT method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Group) Trace

func (g *Group) Trace(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Trace registers a new handler for the given path for TRACE method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

type HandlerFunc

type HandlerFunc func(c *Context)

HandlerFunc is the type which serves HTTP requests.

func WrapHandler

func WrapHandler(h http.Handler) HandlerFunc

WrapHandler wraps a http.Handler and returns a kid.HandlerFunc.

func WrapHandlerFunc

func WrapHandlerFunc(f http.HandlerFunc) HandlerFunc

WrapHandlerFunc wraps a http.HandlerFunc and returns a kid.HandlerFunc.

type Kid

type Kid struct {
	// contains filtered or unexported fields
}

Kid is the struct that holds everything together.

It's a framework instance.

func New

func New() *Kid

New returns a new instance of Kid.

func (*Kid) Add

func (k *Kid) Add(path string, handler HandlerFunc, methods []string, middlewares ...MiddlewareFunc)

Add registers a new handler for the given path for the given methods. Specifying at least one method is required.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Kid) Any

func (k *Kid) Any(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Any registers a new handler for the given path for all of the HTTP methods.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Kid) ApplyOptions

func (k *Kid) ApplyOptions(opts ...Option)

ApplyOptions applies the given options.

func (*Kid) Connect

func (k *Kid) Connect(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Connect registers a new handler for the given path for CONNECT method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Kid) Debug

func (k *Kid) Debug() bool

Debug returns whether we are in debug mode or not.

func (*Kid) Delete

func (k *Kid) Delete(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Delete registers a new handler for the given path for DELETE method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Kid) Get

func (k *Kid) Get(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Get registers a new handler for the given path for GET method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Kid) Group

func (k *Kid) Group(prefix string, middlewares ...MiddlewareFunc) Group

Group creates a new router group.

Specifying middlewares is optional. Middlewares will be applied to all of the group routes.

func (*Kid) Head

func (k *Kid) Head(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Head registers a new handler for the given path for HEAD method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Kid) NewContext

func (k *Kid) NewContext(req *http.Request, res http.ResponseWriter) *Context

NewContext basically is a helper function and can be used in testing.

func (*Kid) Options

func (k *Kid) Options(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Options registers a new handler for the given path for OPTIONS method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Kid) Patch

func (k *Kid) Patch(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Patch registers a new handler for the given path for PATCH method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Kid) Post

func (k *Kid) Post(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Post registers a new handler for the given path for POST method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Kid) Put

func (k *Kid) Put(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Put registers a new handler for the given path for PUT method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Kid) Run

func (k *Kid) Run(addrs ...string) error

Run runs HTTP server.

Specifying an address is optional. Default address is :2376.

func (*Kid) RunTLS added in v0.2.0

func (k *Kid) RunTLS(certFile, keyFile string, addrs ...string) error

Run runs HTTPS server.

Specifying an address is optional. Default address is :2376.

func (*Kid) ServeHTTP

func (k *Kid) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.HandlerFunc interface.

func (*Kid) Shutdown added in v0.2.0

func (k *Kid) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections.

func (*Kid) Static

func (k *Kid) Static(urlPath, staticRoot string, middlewares ...MiddlewareFunc)

Static registers a new route for serving static files.

It uses http.Dir as its file system.

func (*Kid) StaticFS

func (k *Kid) StaticFS(urlPath string, fs http.FileSystem, middlewares ...MiddlewareFunc)

StaticFS registers a new route for serving static files.

It uses the given file system to serve static files.

func (*Kid) Trace

func (k *Kid) Trace(path string, handler HandlerFunc, middlewares ...MiddlewareFunc)

Trace registers a new handler for the given path for TRACE method.

Specifying middlewares is optional. Middlewares will only be applied to this route.

func (*Kid) Use

func (k *Kid) Use(middleware MiddlewareFunc)

Use registers a new middleware. The middleware will be applied to all of the routes.

type Map

type Map map[string]any

Map is a generic map to make it easier to send responses.

type MiddlewareFunc

type MiddlewareFunc func(next HandlerFunc) HandlerFunc

MiddlewareFunc is the type of middlewares.

type Node added in v0.1.0

type Node struct {
	// contains filtered or unexported fields
}

Node is a tree node.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is the interface for customizing Kid.

func WithDebug

func WithDebug(debug bool) Option

WithDebug configures Kid's debug option.

func WithHTMLRenderer

func WithHTMLRenderer(renderer htmlrenderer.HTMLRenderer) Option

WithHTMLRenderer configures Kid's HTML renderer.

func WithJSONSerializer

func WithJSONSerializer(serializer serializer.Serializer) Option

WithJSONSerializer configures Kid's JSON serializer.

func WithMethodNotAllowedHandler

func WithMethodNotAllowedHandler(handler HandlerFunc) Option

WithMethodNotAllowedHandler configures Kid's method not allowed handler.

func WithNotFoundHandler

func WithNotFoundHandler(handler HandlerFunc) Option

WithNotFoundHandler configures Kid's not found handler.

func WithXMLSerializer

func WithXMLSerializer(serializer serializer.Serializer) Option

WithXMLSerializer configures Kid's XML serializer.

type Params

type Params map[string]string

Params is the type of path parameters.

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.Flusher

	// WriteHeaderNow writes status code.
	WriteHeaderNow()

	// Size returns number of bytes written to response.
	Size() int

	// Written returns true if response has already been written otherwise returns false.
	Written() bool

	// Status returns the status code.
	Status() int
}

ResponseWriter is a wrapper for http.ResponseWriter to make using http.ResponseWriter's methods easier.

type Tree added in v0.1.0

type Tree struct {
	// contains filtered or unexported fields
}

Tree is a tree used for routing.

Directories

Path Synopsis
examples
Package htmlrenderer provides an interface and its implementations for rendering HTML pages.
Package htmlrenderer provides an interface and its implementations for rendering HTML pages.
Package serializer provides an interface to read from request body or write to response body.
Package serializer provides an interface to read from request body or write to response body.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL