http

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2023 License: MIT Imports: 14 Imported by: 1

Documentation

Overview

Package http provides functionality and helpers to build http handlers and servers. It is designed to be used on top of Go kit (github.com/go-kit/kit) and the Gorilla web toolkit (github.com/gorilla).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecodeJSONBody

func DecodeJSONBody(r *http.Request, target interface{}) error

Tries to decode the body of the given http request into target.

func DecodeQueryParameters

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

Decodes the query parameters in the url of the given request into v, which should be a pointer to a struct. Struct tags can be used to define custom field names or ignore struct fields (see the "github.com/gorilla/schema" package for more information).

Example:

type X struct {
  A string `schema:"a1"`
  B int `schema:"a2"`
  // Ignore this field
  C int `schema:"-"`
}

func DecodeURLParameter

func DecodeURLParameter(r *http.Request, name string) (string, error)

Returns the value of the given url parameter. This is designed to work with path variables of the "github.com/gorilla/mux" package.

Example:

handlerFunc := func(w http.ResponseWriter, r *http.Request) {
  // If e.g. the url of the request is "/somepath/123abc", then v will equal "123abc".
  v, ok := DecodeURLParameter(r, "xyz")
  ...
}

r := mux.r := mux.NewRouter()
r.HandleFunc("/somepath/{xyz}", handlerFunc)

func EncodeError

func EncodeError(_ context.Context, err error, w http.ResponseWriter) error

Sends an appropriate http status code and response body based on the error. If the error is of type Error from package "github.com/dkinzler/kit/errors" and contains a public error code or message, that information will be encoded as json and sent in the response body.

The json body has the following format:

{
  "error": {
    "code": 42,
	"message": "this is an example error message"
  }
}

func EncodeJSONBody

func EncodeJSONBody(w http.ResponseWriter, source interface{}) error

Encodes the given value as JSON and writes it to the http response.

func ErrToCode

func ErrToCode(err error) int

Determines an appropriate http response code for the given error. If the error is of type Error from package "github.com/dkinzler/kit/errors", the response code is based on the error code of the error. Otherwise http.StatusInternalServerError is returned.

func HandleShutdown

func HandleShutdown(srv *http.Server, closeChan <-chan struct{}, onShutdown func(error), timeout time.Duration) <-chan struct{}

Sets up graceful shutdown for the given http server. Server will be shutdown when a message is received on the given channel. Call this function before invoking ListenAndServe(...) on the server and then read from the returned channel.

Example:

srv := &http.Server{...}

// Shutdown the server when a SIGINT or SIGTERM signal is received, e.g. when the process is killed
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)

shutdown := HandleShutdown(srv, sig, func(err error) {
	// do something on shutdown, e.g. log the error if not nil
})

// When the shutdown handler calls srv.Shutdown(), ListenAndServe will immediately return with http.ErrServerClsoed.
// If ListenAndServe returns another error, terminate the program.
// Otherwise the read on the shutdown channel might block forever since ListenAndServe did not return because of a shutdown signal.
// Alternatively one could pass another channel to HandleShutdown that can be send a value here.
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
	os.Exit(0)
}

//wait for shutdown to complete
<-shutdown

func MakeGenericJSONEncodeFunc

func MakeGenericJSONEncodeFunc(status int) kithttp.EncodeResponseFunc

A generic response encoder function for Go kit (github.com/go-kit/kit). Use this function only if the response value returned by the endpoint implements the Responder interface from package "github.com/dkinzler/kit/endpoint".

func NewMaxRequestBodySizeHandler

func NewMaxRequestBodySizeHandler(next http.Handler, maxBytes int64) http.Handler

Limit the request body size of the given http handler to the specified number of bytes. If the request body is larger, reading beyond the limit will return an error.

func PanicMiddleware

func PanicMiddleware(next http.Handler, onPanic func(e interface{})) http.Handler

Http middleware that recovers and calls the provided onPanic function if the next http handler panics. On panic status code 500 Internal Server Error is written to the response header.

func RunDefaultServer

func RunDefaultServer(handler http.Handler, closeChan <-chan struct{}, config ServerConfig) error

Creates a new http server and starts listening with the given handler, config and useful defaults. Middlewares to catch panics and to timeout requests are added and server shutdown is handled gracefully.

This function blocks until a signal to shutdown the server is received, it then tries to gracefully shutdown the server and eventually returns. We wait for open connections/requests to complete for 10 seconds. The server can be stopped/shut down using the following signals:

  • the program receives a SIGINT signal (e.g. when pressing CTRL+c in a terminal)
  • the program receives a SIGTERM signal (e.g. when the process is killed)
  • a value is sent on closeChan

When using a close channel, make sure to send any values in a non-blocking way.

Returns any errors from ListenAndServer() that are not http.ErrServerClosed.

Types

type LogErrorHandler

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

LogErrorHandler logs errors that occur while processing a http request. It can be passed as a ServerOption when creating a new http server handler with the "github.com/go-kit/kit/transport/http" package.

func NewLogErrorHandler

func NewLogErrorHandler(logger log.Logger) *LogErrorHandler

func (*LogErrorHandler) Handle

func (h *LogErrorHandler) Handle(ctx context.Context, err error)

type ServerConfig

type ServerConfig struct {
	Address string
	// Defaults to 80
	Port int

	// Maximum size of request body in bytes, 0 = no limit, defaults to 128kb
	RequestMaxBodyBytes int
	// Defaults to 128kb
	RequestMaxHeaderBytes int
	// Defaults to 7s
	RequestTimeout time.Duration
	// Defaults to 10s
	WriteTimeout time.Duration
	// Defaults to 10s
	ReadTimeout time.Duration

	// Called when a panic is caught in a http handler
	OnPanicFunc func(interface{})
	// Called when the server is shut down with the error returned by the Shutdown() method
	OnShutdownFunc func(error)
}

func NewServerConfig

func NewServerConfig() ServerConfig

func (ServerConfig) WithAddress

func (s ServerConfig) WithAddress(address string) ServerConfig

func (ServerConfig) WithOnPanicFunc

func (s ServerConfig) WithOnPanicFunc(onPanic func(interface{})) ServerConfig

func (ServerConfig) WithOnShutdownFunc

func (s ServerConfig) WithOnShutdownFunc(onShutdown func(error)) ServerConfig

func (ServerConfig) WithPort

func (s ServerConfig) WithPort(port int) ServerConfig

func (ServerConfig) WithReadTimeout

func (s ServerConfig) WithReadTimeout(timeout time.Duration) ServerConfig

func (ServerConfig) WithRequestMaxBodyBytes

func (s ServerConfig) WithRequestMaxBodyBytes(maxBytes int) ServerConfig

func (ServerConfig) WithRequestMaxHeaderBytes

func (s ServerConfig) WithRequestMaxHeaderBytes(maxBytes int) ServerConfig

func (ServerConfig) WithRequestTimeout

func (s ServerConfig) WithRequestTimeout(timeout time.Duration) ServerConfig

func (ServerConfig) WithWriteTimeout

func (s ServerConfig) WithWriteTimeout(timeout time.Duration) ServerConfig

Jump to

Keyboard shortcuts

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