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 ¶
- Constants
- Variables
- func NotFound(w http.ResponseWriter, r *http.Request, _ httprouter.Params) (interface{}, error)
- func SetCORSHeaders(w http.ResponseWriter, _ *http.Request, _ httprouter.Params)
- type Config
- type ErrHTTP
- type Handle
- type RawHandle
- type Server
- func (s *Server) Delete(path string, handle Handle)
- func (s *Server) Get(path string, handle Handle)
- func (s *Server) GetRaw(path string, handle RawHandle)
- func (s *Server) ListenAndServe() error
- func (s *Server) Options(path string, handle Handle)
- func (s *Server) Patch(path string, handle Handle)
- func (s *Server) Post(path string, handle Handle)
- func (s *Server) Put(path string, handle Handle)
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) Shutdown(ctx context.Context) error
Examples ¶
Constants ¶
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 ¶
var ( // ErrorCodeToHTTPCode maps internal error codes to http status code. ErrorCodeToHTTPCode = map[int]int{ errorcode.Ok: http.StatusOK, errorcode.InvalidArgument: http.StatusBadRequest, errorcode.FailedPrecondition: http.StatusBadRequest, errorcode.OutOfRange: http.StatusBadRequest, errorcode.AlreadyExists: http.StatusConflict, errorcode.Aborted: http.StatusConflict, errorcode.PermissionDenied: http.StatusForbidden, errorcode.DeadlineExceeded: http.StatusGatewayTimeout, errorcode.Unknown: http.StatusInternalServerError, errorcode.Internal: http.StatusInternalServerError, errorcode.DataLoss: http.StatusInternalServerError, errorcode.NotFound: http.StatusNotFound, errorcode.Unimplemented: http.StatusNotImplemented, errorcode.Unavailable: http.StatusServiceUnavailable, errorcode.ResourceExhausted: http.StatusTooManyRequests, errorcode.Unauthenticated: http.StatusUnauthorized, } )
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 ¶
NewErrHTTP creates an http error from an internal error.
func NewErrInternalServer ¶
func NewErrInternalServer() ErrHTTP
NewErrInternalServer creates an internal server error.
func (ErrHTTP) JSONMarshal ¶
JSONMarshal marshals an error to JSON.
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 (*Server) ListenAndServe ¶
ListenAndServe starts the server.