vk

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2022 License: Apache-2.0 Imports: 19 Imported by: 23

README

vektor API

vk is the vektor component that allows for easy development of API servers in Go.

Features:

  • HTTPS by default using LetsEncrypt
  • Easy configuration of CORS
  • Built in logging
  • Authentication plug-in point
  • Fast HTTP router built in

Planned:

  • Rate limiter

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RespondBytes added in v0.6.1

func RespondBytes(ctx context.Context, w http.ResponseWriter, data []byte, statusCode int) error

RespondBytes takes the content we want to send back to the client as byte slice, does an early exit for no content, and then straight pipes into the private respondBytes. This is in front of the private func because of pattern consistency and making sure that a 204 with not empty content does not get written to the ResponseWriter.

func RespondJSON added in v0.6.1

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

RespondJSON converts a value to json, and sends it to the client. Ctx is a placeholder here, it is currently unused, but will be used for tracing / logging help purposes later.

func RespondString added in v0.6.1

func RespondString(ctx context.Context, w http.ResponseWriter, data string, statusCode int) error

RespondString sends the data as a raw string to the client. Ctx is a placeholder here, it is currently unused, but will be used for tracing / logging help purposes later.

Types

type Ctx

type Ctx struct {
	Context     context.Context
	Log         *vlog.Logger
	Params      httprouter.Params
	RespHeaders http.Header
	// contains filtered or unexported fields
}

Ctx serves a similar purpose to context.Context, but has some typed fields

func NewCtx

func NewCtx(log *vlog.Logger, params httprouter.Params, headers http.Header) *Ctx

NewCtx creates a new Ctx

func (*Ctx) Get added in v0.2.1

func (c *Ctx) Get(key string) interface{}

Get gets a value from the Ctx's embedded Context (a la key/value store)

func (*Ctx) RequestID added in v0.2.1

func (c *Ctx) RequestID() string

RequestID returns the request ID of the current request, generating one if none exists.

func (*Ctx) Scope added in v0.1.2

func (c *Ctx) Scope() interface{}

Scope retrieves the context's scope

func (*Ctx) Set added in v0.2.1

func (c *Ctx) Set(key string, val interface{})

Set sets a value on the Ctx's embedded Context (a la key/value store)

func (*Ctx) UseRequestID added in v0.2.2

func (c *Ctx) UseRequestID(id string)

UseRequestID is a setter for the request ID

func (*Ctx) UseScope added in v0.1.2

func (c *Ctx) UseScope(scope interface{})

UseScope sets an object to be the scope of the request, including setting the logger's scope the scope can be retrieved later with the Scope() method

type Error

type Error interface {
	Error() string // this ensures all Errors will also conform to the normal error interface

	Message() string
	Status() int
}

Error is an interface representing a failed request

func E

func E(status int, message string) Error

E is Err for those who like terse code

func Err

func Err(status int, message string) Error

Err returns an error with status and message

func Wrap added in v0.1.0

func Wrap(status int, err error) Error

Wrap wraps an error in vk.Error

type ErrorResponse added in v0.1.0

type ErrorResponse struct {
	StatusCode  int    `json:"status"`
	MessageText string `json:"message"`
}

ErrorResponse is a concrete implementation of Error, representing a failed HTTP request

func (*ErrorResponse) Error added in v0.1.0

func (e *ErrorResponse) Error() string

Error returns a full error string

func (*ErrorResponse) Message added in v0.1.0

func (e *ErrorResponse) Message() string

Message returns the error's message

func (*ErrorResponse) Status added in v0.1.0

func (e *ErrorResponse) Status() int

Status returns the error status code

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *http.Request, ctx *Ctx) error

HandlerFunc is the vk version of http.HandlerFunc instead of exposing the ResponseWriter, the function instead returns an object and an error, which are handled as described in `With` below

func CORSHandler added in v0.1.0

func CORSHandler(domain string) HandlerFunc

CORSHandler enables CORS for a route pass "*" to allow all domains, or empty string to allow none

func WrapHandler added in v0.6.1

func WrapHandler(handler HandlerFunc, mw ...Middleware) HandlerFunc

WrapHandler takes an inner HandlerFunc, and a list of Middlewares, and returns a resolved handler that wraps the inner handler at the core with the passed in middlewares from first to last.

For example in the following function call: - WrapHandler(coreHandler, panics, errors, logs, traces)

The wrap would look like this: - incoming request -> traces -> logs -> errors -> panics -> coreHandler

func WrapWebsocket added in v0.6.1

func WrapWebsocket(handler WebSocketHandlerFunc) HandlerFunc

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

Middleware represents a handler that runs on a request before reaching its handler

func ContentTypeMiddleware

func ContentTypeMiddleware(contentType string) Middleware

ContentTypeMiddleware allows the content-type to be set

func ErrorMiddleware added in v0.6.1

func ErrorMiddleware() Middleware

ErrorMiddleware returns a middleware that wraps a handler.

type Options

type Options struct {
	AppName         string `env:"APP_NAME"`
	Domain          string `env:"DOMAIN"`
	HTTPPort        int    `env:"HTTP_PORT"`
	TLSPort         int    `env:"TLS_PORT"`
	TLSConfig       *tls.Config
	EnvPrefix       string
	QuietRoutes     []string
	Logger          *vlog.Logger
	RouterWrapper   RouterWrapper
	FallbackAddress string

	PreRouterInspector func(http.Request)
}

Options are the available options for Server

func (*Options) HTTPPortSet added in v0.3.0

func (o *Options) HTTPPortSet() bool

HTTPPortSet returns true if the HTTP port is set

func (*Options) ShouldUseHTTP added in v0.1.0

func (o *Options) ShouldUseHTTP() bool

ShouldUseHTTP returns true if insecure HTTP should be used

func (*Options) ShouldUseTLS added in v0.3.0

func (o *Options) ShouldUseTLS() bool

ShouldUseTLS returns true if domain is set and/or TLS is configured

type OptionsModifier

type OptionsModifier func(*Options)

OptionsModifier takes an options struct and returns a modified Options struct

func UseAppName

func UseAppName(name string) OptionsModifier

UseAppName allows an app name to be set (for vanity only, really....)

func UseDomain

func UseDomain(domain string) OptionsModifier

UseDomain sets the server to use a particular domain for TLS

func UseEnvPrefix added in v0.2.0

func UseEnvPrefix(prefix string) OptionsModifier

UseEnvPrefix uses the provided env prefix (default VK) when looking up other options such as `VK_HTTP_PORT`

func UseFallbackAddress added in v0.5.3

func UseFallbackAddress(address string) OptionsModifier

UseFallbackAddress takes in an address to use as a fallback proxy address

func UseHTTPPort added in v0.3.0

func UseHTTPPort(port int) OptionsModifier

UseHTTPPort sets the HTTP port to be used: If domain is set, HTTP port will be used for LetsEncrypt challenge server If domain is NOT set, this option will put VK in insecure HTTP mode

func UseInspector added in v0.4.1

func UseInspector(isp func(http.Request)) OptionsModifier

UseInspector sets a function that will be allowed to inspect every HTTP request before it reaches VK's internal router, but cannot modify said request or affect the handling of said request in any way. Use at your own risk, as it may introduce performance issues if not used correctly.

func UseLogger

func UseLogger(logger *vlog.Logger) OptionsModifier

UseLogger allows a custom logger to be used

func UseQuietRoutes added in v0.5.2

func UseQuietRoutes(routes ...string) OptionsModifier

UseQuietRoutes accepts a list of routes to be 'quiet', i.e. no pre- and post-handler logging

func UseRouterWrapper added in v0.5.3

func UseRouterWrapper(wrapper RouterWrapper) OptionsModifier

UseRouterWrapper takes in a RouterWrapper function that takes in an http.Handler, and returns another http.Handler.

func UseTLSConfig added in v0.4.0

func UseTLSConfig(config *tls.Config) OptionsModifier

UseTLSConfig sets a TLS config that will be used for HTTPS This will take precedence over the Domain option in all cases

func UseTLSPort added in v0.4.0

func UseTLSPort(port int) OptionsModifier

UseTLSPort sets the HTTPS port to be used:

type RouteGroup

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

RouteGroup represents a group of routes

func Group

func Group(prefix string) *RouteGroup

Group creates a group of routes with a common prefix and middlewares

func (*RouteGroup) AddGroup

func (g *RouteGroup) AddGroup(group *RouteGroup)

AddGroup adds a group of routes to this group as a subgroup. the subgroup's prefix is added to all of the routes it contains, with the resulting path being "/group.prefix/subgroup.prefix/route/path/here"

func (*RouteGroup) DELETE

func (g *RouteGroup) DELETE(path string, handler HandlerFunc, middleware ...Middleware)

DELETE is a shortcut for server.Handle(http.MethodDelete, path, handler)

func (*RouteGroup) GET

func (g *RouteGroup) GET(path string, handler HandlerFunc, middleware ...Middleware)

GET is a shortcut for server.Handle(http.MethodGet, path, handler, middleware...)

func (*RouteGroup) HEAD

func (g *RouteGroup) HEAD(path string, handler HandlerFunc, middleware ...Middleware)

HEAD is a shortcut for server.Handle(http.MethodHead, path, handler)

func (*RouteGroup) Handle

func (g *RouteGroup) Handle(method, path string, handler HandlerFunc, middleware ...Middleware)

Handle adds a route to be handled

func (*RouteGroup) OPTIONS

func (g *RouteGroup) OPTIONS(path string, handler HandlerFunc, middleware ...Middleware)

OPTIONS is a shortcut for server.Handle(http.MethodOptions, path, handler)

func (*RouteGroup) PATCH

func (g *RouteGroup) PATCH(path string, handler HandlerFunc, middleware ...Middleware)

PATCH is a shortcut for server.Handle(http.MethodPatch, path, handler)

func (*RouteGroup) POST

func (g *RouteGroup) POST(path string, handler HandlerFunc, middleware ...Middleware)

POST is a shortcut for server.Handle(http.MethodPost, path, handler)

func (*RouteGroup) PUT

func (g *RouteGroup) PUT(path string, handler HandlerFunc, middleware ...Middleware)

PUT is a shortcut for server.Handle(http.MethodPut, path, handler)

func (*RouteGroup) WebSocket added in v0.5.3

func (g *RouteGroup) WebSocket(path string, handler WebSocketHandlerFunc)

WebSocket adds a websocket route to be handled.

func (*RouteGroup) WithMiddlewares added in v0.6.1

func (g *RouteGroup) WithMiddlewares(middleware ...Middleware) *RouteGroup

WithMiddlewares takes a list of Middlewares and will apply all of them to every handler in the group. Like in the WrapHandler, the first middleware is going to be the closest to each of the handlers in the group.

Use this for general middlewares like logging, panic recovery, error handling, and tracing. Use the individual handler middlewares for endpoint specific things, like authentication.

type Router

type Router struct {
	*RouteGroup // the "root" RouteGroup that is mounted at server start
	// contains filtered or unexported fields
}

Router handles the responses on behalf of the server

func NewRouter added in v0.4.1

func NewRouter(logger *vlog.Logger, fallback string) *Router

NewRouter creates a new Router

func (*Router) Finalize added in v0.4.1

func (rt *Router) Finalize()

Finalize mounts the root group to prepare the Router to handle requests

func (*Router) HandleHTTP added in v0.1.2

func (rt *Router) HandleHTTP(method, path string, handler http.HandlerFunc)

HandleHTTP handles a classic Go HTTP handlerFunc

func (*Router) ServeHTTP

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

ServeHTTP serves HTTP requests

type RouterWrapper added in v0.5.3

type RouterWrapper func(handler http.Handler) http.Handler

RouterWrapper provides a function signature to implement wrappers for routing. A good use case is to pass in an opentelemetry mux wrapper.

type Server

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

Server represents a vektor API server

func New

func New(opts ...OptionsModifier) *Server

New creates a new vektor API server

func (*Server) AddGroup added in v0.4.1

func (s *Server) AddGroup(group *RouteGroup)

AddGroup adds a RouteGroup to be handled

func (*Server) CanHandle added in v0.4.1

func (s *Server) CanHandle(method, path string) bool

CanHandle returns true if the server can handle a given method and path

func (*Server) DELETE added in v0.4.1

func (s *Server) DELETE(path string, handler HandlerFunc)

DELETE is a shortcut for router.Handle(http.MethodDelete, path, handle)

func (*Server) GET added in v0.4.1

func (s *Server) GET(path string, handler HandlerFunc)

GET is a shortcut for router.Handle(http.MethodGet, path, handle)

func (*Server) HEAD added in v0.4.1

func (s *Server) HEAD(path string, handler HandlerFunc)

HEAD is a shortcut for router.Handle(http.MethodHead, path, handle)

func (*Server) Handle added in v0.4.1

func (s *Server) Handle(method, path string, handler HandlerFunc)

Handle adds a route to be handled

func (*Server) HandleHTTP added in v0.4.1

func (s *Server) HandleHTTP(method, path string, handler http.HandlerFunc)

HandleHTTP allows vk to handle a standard http.HandlerFunc

func (*Server) OPTIONS added in v0.4.1

func (s *Server) OPTIONS(path string, handler HandlerFunc)

OPTIONS is a shortcut for router.Handle(http.MethodOptions, path, handle)

func (*Server) PATCH added in v0.4.1

func (s *Server) PATCH(path string, handler HandlerFunc)

PATCH is a shortcut for router.Handle(http.MethodPatch, path, handle)

func (*Server) POST added in v0.4.1

func (s *Server) POST(path string, handler HandlerFunc)

POST is a shortcut for router.Handle(http.MethodPost, path, handle)

func (*Server) PUT added in v0.4.1

func (s *Server) PUT(path string, handler HandlerFunc)

PUT is a shortcut for router.Handle(http.MethodPut, path, handle)

func (*Server) ServeHTTP added in v0.4.1

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves HTTP requests using the internal router while allowing said router to be swapped out underneath at any time in a thread-safe way

func (*Server) Start

func (s *Server) Start() error

Start starts the server listening

func (*Server) Stop added in v0.5.3

func (s *Server) Stop() error

Stop shuts down the server and returns any associated errors

func (*Server) StopCtx added in v0.5.3

func (s *Server) StopCtx(ctx context.Context) error

StopCtx shuts down the server (with a context) and returns any associated errors

func (*Server) SwapRouter added in v0.4.1

func (s *Server) SwapRouter(router *Router)

SwapRouter allows swapping VK's router out in realtime while continuing to serve requests in the background

func (*Server) TestStart added in v0.5.0

func (s *Server) TestStart() error

TestStart "starts" the server for automated testing with vtest

func (*Server) WebSocket added in v0.5.3

func (s *Server) WebSocket(path string, handler WebSocketHandlerFunc)

WebSocket registers a WebSocket handler

type WebSocketHandlerFunc added in v0.5.3

type WebSocketHandlerFunc func(*http.Request, *Ctx, *websocket.Conn) error

WebSocketHandlerFunc is the vk version of http.HandlerFunc, but specifically for websockets. Instead of exposing the ResponseWriter, the function exposes a Gorilla `Conn`.

Directories

Path Synopsis
cmd
This package spawns a real HTTP server based on the test suite in the parent directory.
This package spawns a real HTTP server based on the test suite in the parent directory.

Jump to

Keyboard shortcuts

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