ivy

package module
v0.0.0-...-0d87383 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2025 License: Apache-2.0 Imports: 7 Imported by: 0

README

IVY: net/http based router implementation with fiber like API

Features

  • Standard HTTP methods based functions that allow easy creation of routes
  • Allows returning error from handlers, and handling it globally, instead of doing http.Error(w, err.Error(), 500) everywhere in your handler
  • SubRouters and seamless mounting into one another
  • Simpler Abstractions to write HTTP responses
  • Middleware support
  • Request Level Key-Value store to pass data from a middleware to next middleware

Usage

router := ivy.NewRouter()

// optional, if want to change default error handler
router.ErrorHandler = func(c *ivy.Context, err error) {
    c.Status(500).SendString(fmt.Sprintf("[ERROR HANDLER]: %s", err.Error()))
}

// for middlewares
router.Use(func (c *ivy.Context) error {
	return c.Next()
})

// http methods
router.Get("/ping", func(c *ivy.Context) error {
	return c.SendString("OK ! from router 1")
})

// router mounting
router2 := ivy.NewRouter()
router2.Get("/_ping",
	// middleware 1
	func(c *ivy.Context) error {
		logger.Info("INSIDE middleware 1")
		c.KV.Set("hello", "world")
		return c.Next()
	},

	// middleware 2
	func(c *ivy.Context) error {
		logger.Info("INSIDE middleware 2")
		return c.Next()
	},

	// handler
	func(c *ivy.Context) error {
		return c.SendString(fmt.Sprintf("OK! from router 2 (hello = %v)", c.KV.Get("hello")))
	},
)

// mouting router into another router
router.Mount("/v2", router2)

// start server with ivy route, just like mux
http.ListenAndServe(":8080", router)

Examples

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// JSONEncoder defaults to [encoding/json.Marshal](https://pkg.go.dev/encoding/json#Marshal)
	JSONEncoder func(v any) ([]byte, error) = json.Marshal

	// JSONDecoder defaults to [encoding/json.Unmarshal](https://pkg.go.dev/encoding/json#Unmarshal)
	JSONDecoder func(b []byte, v any) error = json.Unmarshal
)

Package level variables, it mainly just introduces a constraint that there will be same encoders across the package in an application lifecycle

Functions

func ErrorFormatJSON

func ErrorFormatJSON(err error) map[string]any

func GetRequestCtxKey

func GetRequestCtxKey() requestKey

func ToHTTPHandler

func ToHTTPHandler(h Handler) http.Handler

Types

type Context

type Context struct {

	// Alias to request.Context()
	// It allows user to pass Context in place of context.Context
	context.Context

	// per-request key value store
	KV *KV
	// contains filtered or unexported fields
}

func NewContext

func NewContext(r *http.Request, w http.ResponseWriter) *Context

func (*Context) AllCookies

func (c *Context) AllCookies() []*http.Cookie

func (*Context) Body

func (c *Context) Body() io.ReadCloser

func (*Context) BodyParser

func (c *Context) BodyParser(v any) error

BodyParser is alias for ParseBodyInto

func (*Context) ClearCookie

func (c *Context) ClearCookie(key string)

func (*Context) Flush

func (c *Context) Flush()

func (*Context) GetCookie

func (c *Context) GetCookie(name string) (*http.Cookie, error)

func (*Context) GetHeaders

func (c *Context) GetHeaders() http.Header

GetHeaders() is http request headers

func (*Context) JSON

func (c *Context) JSON(s any) error

JSON is alias for SendJSON

func (*Context) Next

func (c *Context) Next() error

Calling Next() calls the next middleware in request handler chain

func (*Context) ParseBodyInto

func (c *Context) ParseBodyInto(v any) error

func (*Context) PathParam

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

PathParam is like this `id` in this route path `/resource/{id}`

func (*Context) QueryParam

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

QueryParam is like this `id` in this route path `/resource?id=hello-world`

func (*Context) Request

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

Request() returns original http request for feature parity, until ivy gets a rigid API design

func (*Context) ResponseWriter

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

ResponseWriter() returns original http response writer for feature parity, until ivy gets a rigid API design

func (*Context) SendBytes

func (c *Context) SendBytes(b []byte) error

func (*Context) SendFile

func (c *Context) SendFile(fp string) error

func (*Context) SendHTML

func (c *Context) SendHTML(s []byte) error

func (*Context) SendJSON

func (c *Context) SendJSON(s any) error

func (*Context) SendStatus

func (c *Context) SendStatus(code int) error

func (*Context) SendString

func (c *Context) SendString(s string) error

func (*Context) SetCookie

func (c *Context) SetCookie(cookie *http.Cookie)

func (*Context) SetHeader

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

SetHeaders() set http response headers

func (*Context) SetResponseWriter

func (c *Context) SetResponseWriter(rw http.ResponseWriter)

func (*Context) Status

func (c *Context) Status(code int) *Context

Status(int) let's you set status codes for your responses use it like `c.Status(201).SendString("OK")`

func (*Context) URL

func (c *Context) URL() *url.URL

func (*Context) Write

func (c *Context) Write(p []byte) (n int, err error)

Write implements io.Writer.

func (*Context) Writer

func (c *Context) Writer() io.Writer

type ErrorHandler

type ErrorHandler func(c *Context, err error)
var DefaultErrorHandler ErrorHandler = func(c *Context, err error) {
	http.Error(c.ResponseWriter(), err.Error(), http.StatusInternalServerError)
}

type Handler

type Handler func(c *Context) error

func ToIvyHandler

func ToIvyHandler(h http.Handler) Handler

func (Handler) ServeHTTP

func (hf Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

type KV

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

func (*KV) All

func (kv *KV) All() map[any]any

func (*KV) Get

func (kv *KV) Get(k any) any

Get fetches the value of key in request level KV store in case, key is not present default value is returned

func (*KV) Lookup

func (kv *KV) Lookup(k any) (any, bool)

Lookup fetches the value of key in request level KV store in case default value is not present, ok will be false

func (*KV) Set

func (kv *KV) Set(k any, v any)

Set sets a key into the request level Key-Value store

type Router

type Router struct {
	ErrorHandler ErrorHandler
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter() *Router

NewRouter() creates an ivy.Router with some defaults

func (*Router) Delete

func (r *Router) Delete(path string, handlers ...Handler)

func (*Router) Get

func (r *Router) Get(path string, handlers ...Handler)

func (*Router) Handle

func (r *Router) Handle(path string, handler http.Handler)

func (*Router) HandleFunc

func (r *Router) HandleFunc(path string, handle http.HandlerFunc)

func (*Router) Head

func (r *Router) Head(path string, handlers ...Handler)

func (*Router) Method

func (r *Router) Method(method string, path string, handlers ...Handler)

func (*Router) Mount

func (r *Router) Mount(path string, h http.Handler)

func (*Router) Post

func (r *Router) Post(path string, handlers ...Handler)

func (*Router) Put

func (r *Router) Put(path string, handlers ...Handler)

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements http.Handler.

func (*Router) Use

func (r *Router) Use(handlers ...Handler)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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