tea

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2018 License: GPL-2.0 Imports: 11 Imported by: 2

README

Tea

Tea is a utility library intended to help improve the flow of your Go HTTP servers. Tea goes well with Chi, but works well with the standard lib.

Install

go get -u github.com/blockloop/tea

Docs

Godoc

Example

package main

import (
	"net/http"

	"github.com/go-chi/chi"
	"github.com/blockloop/tea"
)

func main() {
	r := chi.NewRouter()
	// use the JSON handler provided by tea
	r.NotFound(tea.NotFound)
	r.Get("/brewery/{id}", tea.Handler(GetBrewery))
	r.Post("/brewery", tea.Handler(PostBrewery))

	http.ListenAndServe(":3000", r)
}

func GetBrewery(w http.ResponseWriter, r *http.Request) (int, interface{}) {
        id, err := tea.URLInt(r, "id", "required,gt=0")
        if err != nil {
                return tea.StatusError(404)
        }

        brewery, err := db.GetBrewery(id)
        if err != nil {
                log.WithError(err).Error("failed to get brewery from db")
                return tea.StatusError(500)
        }

        return 200, brewery
}

type PostBreweryRequest struct {
        Name string `json:"name" validate:"required"`
        City string `json:"city" validate:"required"`
}

func PostBrewery(w http.ResponseWriter, r *http.Request) (int, interface{}) {
        var req PostBreweryRequest
        // parse the request body as JSON and validate it's struct fields
        err := tea.Body(r, &req)
        if err != nil {
                return tea.Error(400, err)
        }

        // create with db
        if err != nil {
                log.WithError(err).Error("failed to create brewery")
                return tea.StatusError(500)
        }

        return 200, brewery
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNoURLParam = fmt.Errorf("url param does not exist")

ErrNoURLParam means you tried to get a URL param that does not exist

View Source
var NewLogger = func(r *http.Request) log.Interface {
	return log.WithFields(log.Fields{
		"request.id": middleware.GetReqID(r.Context()),
		"client.ip":  r.RemoteAddr,
	})
}

NewLogger creates a new logger from an *http.Request. It is used to create a new log.Interface for middleware and when an existing logger does not exist. It is exposed so that it can be overridden

The default NewLogger creates a new logger with the request.id from middleware.GetReqID, and the client.ip from r.RemoteAddr

View Source
var Responder = render.JSON

Responder is the default responder used to write the messages back to the client. It uses render.JSON by default which will respond using JSON encoding. You can set it to render.JSON, render.XML, render.Data, etc. See github.com/go-chi/render for more info

Functions

func Body

func Body(r *http.Request, v interface{}) error

Body parses a JSON request body and validates it's contents

func Handler

Handler wraps a StatusHandlerFunc and returns a standard lib http.HandlerFunc

func Logger

func Logger(r *http.Request) log.Interface

Logger pulls a logger from request context or creates a new one with NewLogger if one does not exist

func LoggerCtx

func LoggerCtx(r *http.Request) (log.Interface, context.Context)

LoggerCtx uses Logger to get a log.Interface and appends it to the request context, returning the new context with the logger value to be retrieved within Handlers

func LoggerMiddleware

func LoggerMiddleware(next http.Handler) http.Handler

LoggerMiddleware appends a logger with request information using LoggerCtx to every request

func MethodNotAllowed

func MethodNotAllowed(w http.ResponseWriter, r *http.Request)

MethodNotAllowed is a handler for 405 requests

func NotFound

func NotFound(w http.ResponseWriter, r *http.Request)

NotFound is a handler for 404 requests

func URLFloat

func URLFloat(r *http.Request, key, validation string) (float64, error)

URLFloat gets a URL parameter from the request and parses it as an float. If the value of the URL parameter is empty then ErrNoURLParam is returned. If parsing passes, then the validation key will be used to validate the value of the float using Validate

func URLInt

func URLInt(r *http.Request, key, validation string) (int, error)

URLInt gets a URL parameter from the request and parses it as an int. If the value of the URL parameter is empty then ErrNoURLParam is returned. If parsing passes, then the validation key will be used to validate the value of the int using Validate

func URLInt64

func URLInt64(r *http.Request, key, validation string) (int64, error)

URLInt64 gets a URL parameter from the request and parses it as an int64. If the value of the URL parameter is empty then ErrNoURLParam is returned. If parsing passes, then the validation key will be used to validate the value of the int64 using Validate

func URLUint

func URLUint(r *http.Request, key, validation string) (uint64, error)

URLUint gets a URL parameter from the request and parses it as an uint64. If the value of the URL parameter is empty then ErrNoURLParam is returned. If parsing passes, then the validation key will be used to validate the value of the uint64 using Validate

Types

type ErrorResponse

type ErrorResponse struct {
	Code int    `json:"code"`
	Err  string `json:"error"`
}

ErrorResponse is a generic response object

func Error

func Error(status int, err string) (int, *ErrorResponse)

Error creates a response message consisting of the status code and the error string provided. The error string will be rendered back to the client. This is ideal for client errors where the client should be informed of the specific error message.

This is useful within StatusHandlerFuncs to quickly break out of the normal flow of code. It also renders the status code in the body of the response which is often very helpful for clients.

Example:

func CreateUser(w http.ResponseWriter, r *http.Request) (int, interface{}) {
	// ...
	if req.Name == "" {
		return Error(400, "name is required")
	}
}

func Errorf added in v1.1.1

func Errorf(status int, format string, v ...interface{}) (int, *ErrorResponse)

Errorf formats the message and returns the *ErrorResponse with the formatted message according to package fmt

func StatusError

func StatusError(status int) (int, *ErrorResponse)

StatusError creates a response message consisting of the status code and the http.StatusText which applies to that code.

This is useful within StatusHandlerFuncs to quickly break out of the normal flow of code

Example:

func(w http.ResponseWriter, r *http.Request) (int, interface{}) {
	u, p, ok := r.BasicAuth()
	if !ok {
		return StatusError(StatusUnauthorized)
	}
}

func (ErrorResponse) Error

func (e ErrorResponse) Error() string

type StatusHandlerFunc

type StatusHandlerFunc func(w http.ResponseWriter, r *http.Request) (int, interface{})

StatusHandlerFunc is a handler that returns a status code and a message body

type Validator

type Validator interface {
	StructCtx(context.Context, interface{}) error
	VarCtx(context.Context, interface{}, string) error
}

Validator is a struct validator used within Body

var NopValidator Validator = &nopValidator{}

NopValidator is a validator that always returns nil and does not do any validation

var Validate Validator = validator.New()

Validate is the Validator used to validate structs within Body

Jump to

Keyboard shortcuts

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