jsonhttp

package
v0.4.8 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2020 License: Apache-2.0 Imports: 13 Imported by: 4

Documentation

Overview

Package jsonhttp defines a simple HTTP server that renders JSON.

Routes can be added by passing a handle that should return JSON serializable data or an error.

Index

Examples

Constants

View Source
const (
	// DefaultReadTimeout is the default read timeout.
	DefaultReadTimeout = 10 * time.Second

	// DefaultWriteTimeout is the default read timeout.
	DefaultWriteTimeout = 10 * time.Second

	// DefaultMaxHeaderBytes is the default max header bytes.
	DefaultMaxHeaderBytes = 1 << 8
)

Variables

Functions

func NotFound

func NotFound(w http.ResponseWriter, r *http.Request, _ httprouter.Params) (interface{}, error)

NotFound is a handle for a route that is not found.

func SetCORSHeaders added in v0.3.1

func SetCORSHeaders(w http.ResponseWriter, _ *http.Request, _ httprouter.Params)

SetCORSHeaders sets expected CORS headers to allow calls from anywhere.

Types

type Config

type Config struct {
	// The address of the server.
	Address string

	// ReadTimeout is the read timeout.
	ReadTimeout time.Duration

	// WriteTimeout is the read timeout.
	WriteTimeout time.Duration

	// MaxHeaderBytes is the max header bytes.
	MaxHeaderBytes int

	// Optionally, the path to a TLS certificate.
	CertFile string

	// Optionally, the path to a TLS private key.
	KeyFile string

	// Optionally, enable cross-origin requests.
	// By default this will be disabled.
	EnableCORS bool
}

Config contains configuration options for the server.

type ErrHTTP

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

ErrHTTP is an error with an HTTP status code.

func NewErrHTTP

func NewErrHTTP(err error) ErrHTTP

NewErrHTTP creates an http error from an internal error.

func NewErrInternalServer

func NewErrInternalServer() ErrHTTP

NewErrInternalServer creates an internal server error.

func NewErrNotFound

func NewErrNotFound() ErrHTTP

NewErrNotFound creates an error not found.

func (ErrHTTP) Error

func (e ErrHTTP) Error() string

Error implements error.Error.

func (ErrHTTP) JSONMarshal

func (e ErrHTTP) JSONMarshal() []byte

JSONMarshal marshals an error to JSON.

func (ErrHTTP) Status

func (e ErrHTTP) Status() int

Status returns the HTTP status code of the error.

type Handle

type Handle func(http.ResponseWriter, *http.Request, httprouter.Params) (interface{}, error)

Handle is the function type for a route handle.

type RawHandle

type RawHandle func(http.ResponseWriter, *http.Request, httprouter.Params)

RawHandle is the function type for a non-JSON route handle.

type Server

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

Server is the type that implements net/http.Handler.

Example

This example shows how to create a server and add a route with a named param. It also tests the route using net/http/httptest.

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httptest"

	"github.com/julienschmidt/httprouter"

	"github.com/stratumn/go-core/jsonhttp"
)

func main() {
	// Create the server.
	s := jsonhttp.New(&jsonhttp.Config{Address: ":3333"})

	// Add a route with a named param.
	s.Get("/items/:id", func(r http.ResponseWriter, _ *http.Request, p httprouter.Params) (interface{}, error) {
		// Return a map containing the ID.
		result := map[string]string{
			"id": p.ByName("id"),
		}

		return result, nil
	})

	// Create a test server.
	ts := httptest.NewServer(s)
	defer ts.Close()

	// Test our route.
	res, err := http.Get(ts.URL + "/items/one")
	if err != nil {
		log.Fatal(err)
	}

	item, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s", item)
}
Output:

{"id":"one"}

func New

func New(config *Config) *Server

New creates an instance of Server.

func (*Server) Delete

func (s *Server) Delete(path string, handle Handle)

Delete adds a DELETE route.

func (*Server) Get

func (s *Server) Get(path string, handle Handle)

Get adds a GET route.

func (*Server) GetRaw

func (s *Server) GetRaw(path string, handle RawHandle)

GetRaw adds a GET non-JSON route.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts the server.

func (*Server) Options

func (s *Server) Options(path string, handle Handle)

Options adds an OPTIONS route.

func (*Server) Patch

func (s *Server) Patch(path string, handle Handle)

Patch adds a PATCH route.

func (*Server) Post

func (s *Server) Post(path string, handle Handle)

Post adds a POST route.

func (*Server) Put

func (s *Server) Put(path string, handle Handle)

Put adds a PUT route.

func (*Server) ServeHTTP

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

ServeHTTP implements net/http.Handler.ServeHTTP.

func (*Server) Shutdown

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

Shutdown stops the server.

Jump to

Keyboard shortcuts

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