jsonapi

package module
v0.0.0-...-982fa16 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2018 License: MIT Imports: 14 Imported by: 3

README

Build Status codecov Go Report Card godoc

jsonapi

A small library, built on top of fasthttp, fasthttprouter and easyjson.

Quick start

func main() {
	err := jsonapi.
		NewServer().
		Get("/" func(ctx *Ctx) {
		    ctx.WriteJSON()
		}).
		Listen()
	if err != nil {
		log.Fatal(err)
	}
}

Dependencies

jsonapi is not a standalone library, it has some dependencies.

Install

go get -u github.com/skamenetskiy/jsonapi

Documentation

Index

Constants

View Source
const (
	DefaultAddr = ":80"

	MethodGet     = "GET"
	MethodHead    = "HEAD"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodPatch   = "PATCH"
	MethodDelete  = "DELETE"
	MethodConnect = "CONNECT"
	MethodOptions = "OPTIONS"
	MethodTrace   = "TRACE"

	StatusOK                  = 200
	StatusBadRequest          = 400
	StatusUnauthorized        = 401
	StatusForbidden           = 403
	StatusNotFound            = 404
	StatusMethodNotAllowed    = 405
	StatusInternalServerError = 500
	StatusBadGateway          = 502
	StatusServiceUnavailable  = 503
	StatusGatewayTimeout      = 504
)

Variables

View Source
var (
	ErrUnauthorized = NewErrorString("unauthorized", StatusUnauthorized)
)

Functions

This section is empty.

Types

type BaseController

type BaseController struct {
}

BaseController is a helper struct that implements basic response methods that can be used by inheriting controller

func (*BaseController) Err

func (c *BaseController) Err(err error, code int) *Result

Err returns an error response with http code

func (*BaseController) ErrBadGateway

func (c *BaseController) ErrBadGateway(err error) *Result

ErrBadGateway return http error BadGateway

func (*BaseController) ErrBadRequest

func (c *BaseController) ErrBadRequest(err error) *Result

ErrBadRequest return http error BadRequest

func (*BaseController) ErrForbidden

func (c *BaseController) ErrForbidden(err error) *Result

ErrForbidden return http error Forbidden

func (*BaseController) ErrGatewayTimeout

func (c *BaseController) ErrGatewayTimeout(err error) *Result

ErrGatewayTimeout return http error GatewayTimeout

func (*BaseController) ErrInternalServerError

func (c *BaseController) ErrInternalServerError(err error) *Result

ErrInternalServerError return http error InternalServerError

func (*BaseController) ErrMethodNotAllowed

func (c *BaseController) ErrMethodNotAllowed(err error) *Result

ErrMethodNotAllowed return http error MethodNotAllowed

func (*BaseController) ErrNotFound

func (c *BaseController) ErrNotFound(err error) *Result

ErrNotFound returns http error NotFound

func (*BaseController) ErrServiceUnavailable

func (c *BaseController) ErrServiceUnavailable(err error) *Result

ErrServiceUnavailable return http error ServiceUnavailable

func (*BaseController) ErrUnauthorized

func (c *BaseController) ErrUnauthorized(err error) *Result

ErrUnauthorized return http error Unauthorized

func (*BaseController) OK

func (c *BaseController) OK(v json.Marshaler) *Result

OK returns 200 OK response

func (*BaseController) OKBytes

func (c *BaseController) OKBytes(v []byte) *Result

Bytes is a method for returning []byte result (for example: raw json as []byte)

func (*BaseController) OKList

func (c *BaseController) OKList(v []json.Marshaler) *Result

List is a method for returning list of []json.Marshaler without the need to create a custom struct wrapper

func (*BaseController) OKString

func (c *BaseController) OKString(v string) *Result

String is a method for returning string result (for example: raw json as string)

type BytesResult

type BytesResult []byte

BytesResult is a wrapper for bytes to return it as json.Marshaler

func (BytesResult) MarshalJSON

func (b BytesResult) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

type CRUDClient

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

func NewCRUDClient

func NewCRUDClient(addr string, path string) *CRUDClient

func (*CRUDClient) Create

func (c *CRUDClient) Create(v CRUDModel) error

func (*CRUDClient) Delete

func (c *CRUDClient) Delete(id ID)

func (*CRUDClient) Get

func (c *CRUDClient) Get(v CRUDModel) error

func (*CRUDClient) GetByID

func (c *CRUDClient) GetByID(id ID, v CRUDModel)

func (*CRUDClient) Update

func (c *CRUDClient) Update(id ID, v CRUDModel)

type CRUDController

type CRUDController interface {
	Create(*Ctx) *Result  // POST   /path
	Get(*Ctx) *Result     // GET    /path
	GetByID(*Ctx) *Result // GET    /path/:id
	Update(*Ctx) *Result  // PUT    /path/:id
	Delete(*Ctx) *Result  // DELETE /path/:id
}

CRUDController interface defines a basic CRUDController controller

type CRUDModel

type CRUDModel interface {
	json.Marshaler
	json.Unmarshaler
	GetID() ID
	SetID(id ID)
}

type Client

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

Client describes jsonapi client

func NewClient

func NewClient(addr string) *Client

NewClient generates a new jsonapi client

func (*Client) Delete

func (c *Client) Delete(uri string) (*Response, error)

Delete is making http DELETE request

func (*Client) Get

func (c *Client) Get(uri string) (*Response, error)

Get is making a http GET request

func (*Client) Post

func (c *Client) Post(uri string, body json.Marshaler) (*Response, error)

Post is making http POST request

func (*Client) Put

func (c *Client) Put(uri string, body json.Marshaler) (*Response, error)

Put is making http PUT request

func (*Client) Request

func (c *Client) Request() *Request

Request returns a new *Request object

func (*Client) SetAuthFunc

func (c *Client) SetAuthFunc(authFunc ClientAuthFunc) *Client

SetAuthFunc sets authentication modifier function

func (*Client) UseSSL

func (c *Client) UseSSL() *Client

UseSSL forces the client to use https protocol

type ClientAuthFunc

type ClientAuthFunc func(*Request)

ClientAuthFunc is modifying the client request to implement authentication in client

type Controller

type Controller interface {
	Methods() ControllerMethods // should return controller methods
}

Controller interface

type ControllerHandler

type ControllerHandler func(*Ctx) *Result

ControllerHandler defines controller handler func

type ControllerMethods

type ControllerMethods map[string]ControllerPaths

ControllerMethods is a map linking http method to controller paths

type ControllerPaths

type ControllerPaths map[string]ControllerHandler

ControllerPaths is a map linking path to handler

type Ctx

type Ctx struct {
	*fasthttp.RequestCtx
}

Ctx is a wrapper for fasthttp.RequestCtx

func (*Ctx) Err

func (c *Ctx) Err(err error, code int)

Err is writing an error to response body with code

func (*Ctx) ErrBadGateway

func (c *Ctx) ErrBadGateway(err error)

ErrBadGateway writes http error BadGateway to response body

func (*Ctx) ErrBadRequest

func (c *Ctx) ErrBadRequest(err error)

ErrBadRequest writes http error BadRequest to response body

func (*Ctx) ErrForbidden

func (c *Ctx) ErrForbidden(err error)

ErrForbidden writes http error Forbidden to response body

func (*Ctx) ErrGatewayTimeout

func (c *Ctx) ErrGatewayTimeout(err error)

ErrGatewayTimeout writes http error GatewayTimeout to response body

func (*Ctx) ErrInternalServerError

func (c *Ctx) ErrInternalServerError(err error)

ErrInternalServerError writes http error InternalServerError to response body

func (*Ctx) ErrMethodNotAllowed

func (c *Ctx) ErrMethodNotAllowed(err error)

ErrMethodNotAllowed writes http error MethodNotAllowed to response body

func (*Ctx) ErrNotFound

func (c *Ctx) ErrNotFound(err error)

ErrNotFound writes http error NotFound to response body

func (*Ctx) ErrServiceUnavailable

func (c *Ctx) ErrServiceUnavailable(err error)

ErrServiceUnavailable writes http error ServiceUnavailable to response body

func (*Ctx) ErrUnauthorized

func (c *Ctx) ErrUnauthorized(err error)

ErrUnauthorized writes http error Unauthorized to response body

func (*Ctx) GetHeader

func (c *Ctx) GetHeader(k string) string

GetHeader returns a request header

func (*Ctx) GetParamFloat64

func (c *Ctx) GetParamFloat64(k string) (float64, error)

GetParamFloat64 returns path parameter k as float64 or error

func (*Ctx) GetParamInt

func (c *Ctx) GetParamInt(k string) (int, error)

GetParamInt returns path parameter k as int or error

func (*Ctx) GetParamInt64

func (c *Ctx) GetParamInt64(k string) (int64, error)

GetParamInt64 returns path parameter k as int64 or error

func (*Ctx) GetParamString

func (c *Ctx) GetParamString(k string) string

GetParamString returns path parameter k as string

func (*Ctx) GetParamUint64

func (c *Ctx) GetParamUint64(k string) (uint64, error)

GetParamUint64 returns path parameter k as uint64 or error

func (*Ctx) OK

func (c *Ctx) OK(v json.Marshaler)

OK is writing the response to response body with http status 200OK

func (*Ctx) ReadJSON

func (c *Ctx) ReadJSON(v json.Unmarshaler) error

ReadJSON will try to read request body into v

func (*Ctx) SetHeader

func (c *Ctx) SetHeader(k string, v string)

SetHeader sets a response header

func (*Ctx) WriteJSON

func (c *Ctx) WriteJSON(v json.Marshaler)

WriteJSON will try to write v to response body or will output default error if marshal fails

type Error

type Error struct {
	Err  string `json:"error"`
	Code int    `json:"code,omitempty"`
}

Error is a custom error object

func NewError

func NewError(err error, code ...int) *Error

NewError returns a new *Error object

func NewErrorString

func NewErrorString(err string, code ...int) *Error

func (Error) Error

func (e Error) Error() string

Error implements error interface

func (Error) MarshalEasyJSON

func (v Error) MarshalEasyJSON(w *jwriter.Writer)

MarshalEasyJSON supports easyjson.Marshaler interface

func (Error) MarshalJSON

func (v Error) MarshalJSON() ([]byte, error)

MarshalJSON supports json.Marshaler interface

func (*Error) UnmarshalEasyJSON

func (v *Error) UnmarshalEasyJSON(l *jlexer.Lexer)

UnmarshalEasyJSON supports easyjson.Unmarshaler interface

func (*Error) UnmarshalJSON

func (v *Error) UnmarshalJSON(data []byte) error

UnmarshalJSON supports json.Unmarshaler interface

type Handler

type Handler func(*Ctx)

Handler defines the handler func

type ID

type ID interface{}

type ListResult

type ListResult []json.Marshaler

ListResult is a wrapper for []json.Marshaler to return a list without declaring a custom struct for the list

func (ListResult) MarshalJSON

func (l ListResult) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

type Request

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

Request is the request object

func (*Request) Do

func (r *Request) Do() (*Response, error)

Do executes the http request and returns *Response or error if the request failed

func (*Request) SetBody

func (r *Request) SetBody(body []byte) *Request

SetBody is setting request body bytes

func (*Request) SetHeader

func (r *Request) SetHeader(k string, v string) *Request

SetHeader is setting a new request header

func (*Request) SetHeaders

func (r *Request) SetHeaders(headers map[string]string) *Request

SetHeaders is setting(replacing) request headers map

func (*Request) SetMethod

func (r *Request) SetMethod(method string) *Request

SetMethod is setting request method

func (*Request) SetURI

func (r *Request) SetURI(uri string) *Request

SetURI is setting request uri(path)

type Response

type Response struct {
	*fasthttp.Response
}

Response is a wrapper for *fasthttp.Response it adds some useful methods for working with json

func (*Response) ReadJSON

func (r *Response) ReadJSON(v json.Unmarshaler) error

ReadJSON reads json into v from request body

type Result

type Result struct {
	Data json.Marshaler
	Err  *Error
}

Result is an object returned from controller method If Err is not nil, an error will be returned to the client

func (*Result) Error

func (r *Result) Error(err *Error) *Result

Error sets an err to result and return the result

func (*Result) HasError

func (r *Result) HasError() bool

HasError returns TRUE if the result contains an error

type Server

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

Server is an http server wrapper

func NewServer

func NewServer(addr ...string) *Server

NewServer creates a new jsonapi Server

func (*Server) CRUDController

func (s *Server) CRUDController(path string, ctrl CRUDController) *Server

CRUDController assigns a crud controller to a path

func (*Server) Connect

func (s *Server) Connect(p string, handler Handler) *Server

Connect is a shortcut to Route("CONNECT"...)

func (*Server) Controller

func (s *Server) Controller(basePath string, ctrl Controller) *Server

Controller registers a controller

func (*Server) ControllerMethod

func (s *Server) ControllerMethod(method string, p string, handler ControllerHandler) *Server

ControllerMethod registers a controller method handler by http method and path This method can be called directly without a controller.

func (*Server) Delete

func (s *Server) Delete(p string, handler Handler) *Server

Delete is a shortcut to Route("DELETE"...)

func (*Server) Get

func (s *Server) Get(p string, handler Handler) *Server

Get is a shortcut to Route("GET"...)

func (*Server) GetAddr

func (s *Server) GetAddr() string

func (*Server) Head

func (s *Server) Head(p string, handler Handler) *Server

Head is a shortcut to Route("HEAD"...)

func (*Server) Listen

func (s *Server) Listen() error

Listen starts http server and listens on defined addr

func (*Server) ListenTLS

func (s *Server) ListenTLS(certFile string, keyFile string) error

ListenTLS starts http server and listens on defined addr with TLS Reads TLS certificate from certFile and key from keyFile

func (*Server) ListenTLSEmbed

func (s *Server) ListenTLSEmbed(cert []byte, key []byte) error

ListenTLSEmbed starts http server and listens on defined addr with TLS Accepts TLS certificate in cert and key in key

func (*Server) ListenUNIX

func (s *Server) ListenUNIX(mode os.FileMode) error

ListenUNIX starts http server and listens on UNIX socket Accepts mode as file mode

func (*Server) Options

func (s *Server) Options(p string, handler Handler) *Server

Options is a shortcut to Route("OPTIONS"...)

func (*Server) Patch

func (s *Server) Patch(p string, handler Handler) *Server

Patch is a shortcut to Route("PATCH"...)

func (*Server) Post

func (s *Server) Post(p string, handler Handler) *Server

Post is a shortcut to Route("POST"...)

func (*Server) Put

func (s *Server) Put(p string, handler Handler) *Server

Put is a shortcut to Route("PUT"...)

func (*Server) Route

func (s *Server) Route(method string, p string, handler Handler) *Server

Route adds a new route handler to router

func (*Server) SetAddr

func (s *Server) SetAddr(addr string) *Server

SetAddr sets listen address

func (*Server) SetAuthFunc

func (s *Server) SetAuthFunc(authFunc ServerAuthFunc)

SetAuthFunc sets authentication func that will be triggered on every request to the server

func (*Server) SetListener

func (s *Server) SetListener(ln net.Listener) *Server

SetListener sets net.Listener that will be used

func (*Server) Trace

func (s *Server) Trace(p string, handler Handler) *Server

Trace is a shortcut to Route("TRACE"...)

type ServerAuthFunc

type ServerAuthFunc func(*Ctx) bool

ServerAuthFunc is checking the server request for authentication and returns a bool

type StringResult

type StringResult string

StringResult is a wrapper for string to return it json.Marshaler

func (StringResult) MarshalJSON

func (s StringResult) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

Jump to

Keyboard shortcuts

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