jsonserver

package module
v0.0.0-...-02ce73a Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2021 License: GPL-3.0 Imports: 14 Imported by: 0

README

jsonserver

Build Status Coverage Status GoDoc

jsonserver is a simple Golang HTTP server and routing component that can be used to create a JSON API.

An example of basic usage with a couple of routes is:

package main

import (
    "context"
    "net/http"
    "net/url"

    "github.com/D-L-M/jsonserver"
)

func main() {

    port := 9999
    timeout := 30
    middleware := []jsonserver.Middleware{authenticationMiddleware}

    server := jsonserver.NewServer()

    server.EnableTLS("/path/to/ssl/cert", "/path/to/ssl/key")
    server.RegisterRoute("GET", "/", middleware, index)
    server.RegisterRoute("GET", "/products/{id}", middleware, products)

    server.Start(port, timeout)

    select{}

}

// Middleware to ensure that the user is logged in
func authenticationMiddleware(ctx context.Context, request *http.Request, response http.ResponseWriter, body *[]byte) (bool, int) {

    if /* some authentication logic */ {
        return true, 0
    }

    return false, 401 // Failure and HTTP code to send back

}

// Index route
func index(ctx context.Context, request *http.Request, response http.ResponseWriter, body *[]byte) {

    responseBody := jsonserver.JSON{"categories": "/categories", "basket": "/shopping-basket", "logout": "/log-out"}

    jsonserver.WriteResponse(response, &responseBody, http.StatusOK)

}

// Product route
func products(ctx context.Context, request *http.Request, response http.ResponseWriter, body *[]byte) {

    product := GetProduct(ctx.Value("routeParams").(RouteParams)["id"])
    responseBody := jsonserver.JSON{"id": product.ID, "name": product.Name, "price": product.Price}

    jsonserver.WriteResponse(response, &responseBody, http.StatusOK)

}

Middleware

Middleware (if assigned) can block execution of a route if it returns false, and also returns the HTTP status code that will be returned to the client.

Middleware slices are executed in the order that they are specified, so it would make sense, for example, to list generic login middleware prior to permission-checking middleware — the first one to fail will halt execution of the route and any other middleware in the slice will not be run.

HTTP Methods

The HTTP method on which a route will listen is provided as the first argument to server.RegisterRoute(). To register a route against multiple HTTP methods you can provide them in the following format: GET|OPTIONS|DELETE.

Route Parameters

The values of named {wildcard} fragments in routes are provided in the routeParams context value, where the wildcard names (excluding curly braces) form the keys.

If a route path ends with /: all URL fragments at (and following) that point are collected into a route parameter named {catchAll} (with curly braces).

Query Parameters

Query string parameters from a URL are made available as a *url.Values pointer in the queryParams context value.

Request State

A *jsonserver.RequestState pointer is made available in the state context value. It has Set() and Get() methods available that allow any state data to be stored for the duration of the associated request.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WriteResponse

func WriteResponse(response http.ResponseWriter, body *JSON, statusCode int)

WriteResponse writes a JSON response back to the client

Types

type JSON

type JSON map[string]interface{}

JSON represents JSON documents in map form

type Middleware

type Middleware func(ctx context.Context, request *http.Request, response http.ResponseWriter, body *[]byte) (bool, int)

Middleware is a function signature for HTTP middleware that can be assigned to routes

type RequestState

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

RequestState allows storage of miscellaneous state objects that can be referred to throughout a request

func (*RequestState) Get

func (requestState *RequestState) Get(key string) interface{}

Get obtains a state value (or nil if it does not exist)

func (*RequestState) Set

func (requestState *RequestState) Set(key string, value interface{})

Set stores a state value

type Route

type Route struct {
	Path       string
	Action     RouteAction
	Middleware []Middleware
}

Route structs define executable HTTP routes

func (*Route) MatchesPath

func (route *Route) MatchesPath(path string) (bool, RouteParams)

MatchesPath checks whether the route's path matches a given path and returns any wildcard values

type RouteAction

type RouteAction func(ctx context.Context, request *http.Request, response http.ResponseWriter, body *[]byte)

RouteAction is a function signature for actions carried out when a route is matched

type RouteParams

type RouteParams map[string]string

RouteParams is an alias for a map to hold route wildcard parameters, where both keys and values will be strings

type Router

type Router struct {
	Routes     map[string][]Route
	RoutesLock sync.RWMutex
}

Router represents an instance of a router

func (*Router) Dispatch

func (router *Router) Dispatch(request *http.Request, response http.ResponseWriter, method string, path string, params string, body *[]byte) (bool, int, error)

Dispatch will search for and execute a route

func (*Router) RegisterRoute

func (router *Router) RegisterRoute(method string, path string, middleware []Middleware, action RouteAction)

RegisterRoute stores a closure to execute against a method and path

type Server

type Server struct {
	Router   *Router
	CertPath string
	KeyPath  string
}

Server represents a HTTP server

func NewServer

func NewServer() *Server

NewServer creates a new server

func (*Server) EnableTLS

func (server *Server) EnableTLS(certPath string, keyPath string) error

EnableTLS enabled TLS for the server

func (*Server) RegisterRoute

func (server *Server) RegisterRoute(method string, path string, middleware []Middleware, action RouteAction)

RegisterRoute stores a closure to execute against a method and path

func (*Server) ServeHTTP

func (server *Server) ServeHTTP(response http.ResponseWriter, request *http.Request)

Handle incoming requests and route to the appropriate package

func (*Server) Start

func (server *Server) Start(port int, timeout int)

Start initialises the HTTP server

Jump to

Keyboard shortcuts

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