tnyrtr

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2022 License: Unlicense Imports: 12 Imported by: 0

README ¶

📦 tnyrtr

tnyrtr is a simple wrapper around razonyang/fastrouter to save some boilerplate code.

It combines razonyang/fastrouter with convenience functions for sending and parsing JSON, a shutdown channel, a context that offers access to the response status code, the start time of the request, and a traceID (if provided on the request context), as well as the ability to add middlewares.

💻 Example

package main

import (
	"net/http"
	"os"

	"github.com/abecodes/tnyrtr"
	)

func main() {
	// create a shutdown channel
	// any handler can return a tnyrtr.
	shutdown := make(chan os.Signal)
	router := tnyrtr.New(shutdown)

	router.GET(
		"/hello",
		func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
			var user struct {
				name string
			}
			// parse the incoming body
			err := tnyrtr.ParseBodyJSON(r, &user)
			if err != nil {
				// smth went completly wrong and now we need to trigger a graceful server shutdown via the shutdown channel
				return tnyrtr.NewShutdownErr("oO")
			}

			// respond with a JSON
			return tnyrtr.RespondJSON(ctx, w, data, statusCode)
		},
	)

	// IMPORTANT: underlying fastrouter needs to prepare the registered routes
	tnyrtr.Prepare()

  // tnyrtr implements the http.Handler interface
	http.ListenAndServe("localhost:8080",r)

	// somewhere down the line handle the shutdown signal
	<-shutdown
}

🧭 Named parameters

See the fastrouter documentation for more detailed informations on parameter parsing.

router.GET(
		"/hello/<world>",
		func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
			name := tnyrtr.GetParams()["name"]

			fmt.Println(name)
			return nil
		},
	)


âš¡ Middlewares

A router, group, or route can recieve none or many middlewares. They will be applied in the order they are passed.

Middlewares are inherited: router ->group -> route

func Logger(log *log.Logger) tnyrtr.Middleware {
	return func(next tnyrtr.Handler) tnyrtr.Handler {
		return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
			log.Info("REQUEST_START")
			defer func(start time.Time) {
				log.Infow(
					"REQUEST_DONE",
					"STATUS",
					tnyrtr.GetStatus(ctx),
					"DURATION",
					time.Since(start).Seconds(),
				)
			}(tnyrtr.GetTime(ctx))

			return next(ctx, w, r)
		}
	}
}

shutdown := make(chan os.Signal)
// create a router with the logging middleware
router := tnyrtr.New(shutdown, Logger)
// or apply it to a route directly
router.GET("/hello", handler, Logger)

Documentation ¶

Index ¶

Constants ¶

This section is empty.

Variables ¶

This section is empty.

Functions ¶

func GetParams ¶

func GetParams(r *http.Request) map[string]string

GetParams retrieves the named params from a request

func GetStatus ¶

func GetStatus(ctx context.Context) int

GetStatus returns the status code for the request from the context

func GetTime ¶

func GetTime(ctx context.Context) time.Time

GetTime returns the UTC time from the context

func GetTraceID ¶

func GetTraceID(ctx context.Context) string

GetTraceID returns the traceID from the context

func IsShutdown ¶

func IsShutdown(err error) bool

IsShutdown checks if an error is a shutdownErr

func NewShutdownErr ¶

func NewShutdownErr(msg string) error

NewShutdownErr returns an error that will cause an graceful app shutdown

func ParseBodyJSON ¶

func ParseBodyJSON(r *http.Request, val interface{}) error

ParseBodyJSON reads the body of an HTTP request looking for a JSON document. The body is decoded into the provided value.

func RespondJSON ¶

func RespondJSON(ctx context.Context, w http.ResponseWriter, data interface{}, statusCode int) error

RespondJSON converts a Go value to JSON and sends it to the client.

func SetStatusCode ¶

func SetStatusCode(ctx context.Context, statusCode int) error

SetStatusCode sets the satus code for the context

Types ¶

type Handler ¶

Handler handles incoming requests

type Middleware ¶

type Middleware func(next Handler) Handler

Middleware represents a function designed to run some code before/after another handler

type Router ¶

type Router struct {
	// contains filtered or unexported fields
}
Router is a wrapper around a net/http server and the razonyang/fastrouter to tie it together

with a logger and the shutdown channel

func New ¶

func New(shutdown chan os.Signal, mws ...Middleware) *Router

New returns a new router.

func (*Router) DELETE ¶

func (r *Router) DELETE(pth string, handler Handler, mws ...Middleware)

DELETE is a shortcut for group.Handle("DELETE", path, handler)

func (*Router) GET ¶

func (r *Router) GET(pth string, handler Handler, mws ...Middleware)

GET is a shortcut for group.Handle("GET", path, handler)

func (*Router) Group ¶

func (r *Router) Group(sub string, mws ...Middleware) *Router

Group returns a new group

func (*Router) PATCH ¶

func (r *Router) PATCH(pth string, handler Handler, mws ...Middleware)

PATCH is a shortcut for group.Handle("PATCH", path, handler)

func (*Router) POST ¶

func (r *Router) POST(pth string, handler Handler, mws ...Middleware)

POST is a shortcut for group.Handle("POST", path, handler)

func (*Router) PUT ¶

func (r *Router) PUT(pth string, handler Handler, mws ...Middleware)

PUT is a shortcut for group.Handle("PUT", path, handler)

func (*Router) Prepare ¶

func (r *Router) Prepare()

Prepare perpares the registered routes

func (*Router) ServeHTTP ¶

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

ServeHTTP makes the router implement the http.Handler interface.

func (*Router) SignalShutdown ¶

func (r *Router) SignalShutdown()

SignalShutdown sends the app wide terminate signal

type Values ¶

type Values struct {
	TraceID    string
	Now        time.Time
	StatusCode int
}

Values represent state for each request

func GetValues ¶

func GetValues(ctx context.Context) (*Values, error)

GetValues returns the state values from the context

Jump to

Keyboard shortcuts

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