jsonapi

package module
v0.0.0-...-6a31f1c Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2017 License: MIT Imports: 12 Imported by: 0

README

Package jsonapi is simple JSON API implementation for GO. To read more about JSON API format please visit http://jsonapi.org/

Current implementation includes:

  • Marshalling
  • Unmarshalling
  • Links
  • Relations Links
  • Parsing URL Query in json api format
  • JSON API compatible errors
  • Validator

For more details please visit GoDoc https://godoc.org/github.com/vtg/jsonapi

#####Author

VTG - http://github.com/vtg

License

Released under the MIT License.

GoDoc

Documentation

Overview

Package jsonapi is simple JSON API implementation for GO. To read more about JSON API format please visit http://jsonapi.org/

Example:

import (
	"fmt"

	"github.com/vtg/jsonapi"
)

type Post struct {
	ID       uint64        `jsonapi:"id,users"`
	Name     string        `jsonapi:"attr,name"`
	Age      uint32        `jsonapi:"attr,age,string,readonly"` // this will be marshalled as string and will be ignored on unmarshal
	SelfLink string        `jsonapi:"link,self"`
	Comments jsonapi.Links `jsonapi:"rellink,comments"`
}

// BeforeMarshalJSONAPI will be executed before marshalling
func (p *Post) BeforeMarshalJSONAPI() error {
	p.SelfLink = fmt.Sprintf("/api/posts/%d", p.ID)
	p.Comments.Related = fmt.Sprintf("/api/posts/%d/comments", p.ID)
	return nil
}

// AfterUnmarshalJSONAPI will be executed after unmarshalling
func (p *Post) AfterUnmarshalJSONAPI() error {
	v := jsonapi.Validator{}
	v.Present(p.Name, "name")
	return v.Verify()
}

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrorRecordNotFound returns Error for record not found behaviour
	ErrorRecordNotFound = Error{
		Status: "404",
		Title:  "Record Not Found",
		Detail: "The record you are looking for does not exist",
	}
	// ErrorPageNotFound returns Error for page not found behaviour
	ErrorPageNotFound = Error{
		Status: "404",
		Title:  "Page Not Found",
		Detail: "The page you are looking for does not exist",
	}

	// ErrorUnauthorized returns Error for unauthorized request
	ErrorUnauthorized = Error{
		Status: "401",
		Title:  "Unauthorized Request",
		Detail: "You are forbidden from accessing this page",
	}
)

Functions

func Marshal

func Marshal(i interface{}) ([]byte, error)

Marshal item to json api format

func MarshalWithScope

func MarshalWithScope(i interface{}, scope string) ([]byte, error)

MarshalWithScope item to json api format

func Unmarshal

func Unmarshal(b []byte, i interface{}) error

Unmarshal decoding json api compatible request

func UnmarshalWithScope

func UnmarshalWithScope(b []byte, i interface{}, scope string) error

UnmarshalWithScope decoding json api compatible request

Types

type AfterUnmarshaler

type AfterUnmarshaler interface {
	AfterUnmarshalJSONAPI() error
}

AfterUnmarshaler interface

type BeforeMarshaler

type BeforeMarshaler interface {
	BeforeMarshalJSONAPI() error
}

BeforeMarshaler interface

func (p *Post) BeforeMarshalJSONAPI() error {
	p.SelfLink = fmt.Sprintf("/api/posts/%d", p.ID)
	p.Comments.Related = fmt.Sprintf("/api/posts/%d/comments", p.ID)
	return nil
}

type Change

type Change struct {
	Field string
	Cur   string
	New   string
}

Change structure for storing structure changes

type Changes

type Changes []Change

Changes store

func UnmarshalWithChanges

func UnmarshalWithChanges(b []byte, i interface{}) (Changes, error)

UnmarshalWithChanges decoding json api compatible request into structure and returning changes

func UnmarshalWithChangesWithScope

func UnmarshalWithChangesWithScope(b []byte, i interface{}, scope string) (Changes, error)

UnmarshalWithChangesWithScope decoding json api compatible request into structure and returning changes

func (Changes) Contains

func (c Changes) Contains(keys ...string) bool

Contains returns true if changes have field

func (Changes) Empty

func (c Changes) Empty() bool

Empty returns true if there are no changes

func (Changes) Find

func (c Changes) Find(k string) Change

Find changed field by name

type Error

type Error struct {
	Code   string       `json:"code,omitempty"`
	Status string       `json:"status,omitempty"`
	Source *ErrorSource `json:"source,omitempty"`
	Title  string       `json:"title,omitempty"`
	Detail string       `json:"detail,omitempty"`
}

Error type

func ErrorBadRequest

func ErrorBadRequest(details string) Error

ErrorBadRequest creating Error for inprocessible entries

func ErrorForbidden

func ErrorForbidden(details string) Error

ErrorForbidden creating Error for forbidden entries

func ErrorInternal

func ErrorInternal(details string) Error

ErrorInternal creating Error for internal error

func ErrorInvalidAttribute

func ErrorInvalidAttribute(pointer, details string) Error

ErrorInvalidAttribute creating Error for invalid attributes

func (Error) Error

func (e Error) Error() string

Error returns Detail to implement error interface

type ErrorSource

type ErrorSource struct {
	Pointer string `json:"pointer"`
}

ErrorSource type

type Errors

type Errors struct {
	Errors []Error `json:"errors,omitempty"`
}

Errors type

func (*Errors) AddError

func (e *Errors) AddError(err error)

AddError adds Error to errors

func (Errors) Error

func (e Errors) Error() string

Error returns Detail to implement error interface

func (Errors) HasErrors

func (e Errors) HasErrors() bool

HasErrors adds Error to errors

func (Errors) StatusCode

func (r Errors) StatusCode() int

StatusCode returns first error status code or success

type Keymap

type Keymap [2]string

Keymap type for storing key-value

func (Keymap) Key

func (k Keymap) Key() string

Key returns key

func (Keymap) Value

func (k Keymap) Value() string

Value returns value

func (Keymap) Values

func (k Keymap) Values() []string

Values returns value

type Keymaps

type Keymaps []Keymap

Keymaps type

func (Keymaps) Get

func (k Keymaps) Get(key string) (string, bool)

Get returns value for provided key

type Links struct {
	Self    string `json:"self,omitempty"`
	Related string `json:"related,omitempty"`
}

Links structure

type Marshaler

type Marshaler interface {
	MarshalJSONAPI() ([]byte, error)
}

Marshaler interface example

func (p *Post) MarshalJSONAPI() ([]byte, error) {
	return []byte(`{"custom":"return"}`), nil
}

type MetaData

type MetaData struct {
	Total  int         `json:"total"`
	Limit  int         `json:"limit"`
	Offset int         `json:"offset"`
	Data   interface{} `json:"data,omitempty"`
}

MetaData struct

type Query

type Query struct {
	Limit   int
	Offset  int
	Format  string
	Sort    []string
	Filters Keymaps
	Queries Keymaps
	Include string
	Start   *time.Time
	End     *time.Time
}

Query contains parsed url query params

func QueryParams

func QueryParams(m map[string][]string) *Query

QueryParams takes URL params and returns parsed params for jsonapi

func (*Query) AddFilter

func (q *Query) AddFilter(key, value string)

AddFilter adds key/value pair to filter array

func (*Query) AddQuery

func (q *Query) AddQuery(key, value string)

AddQuery adds key/value pair to queries array

func (*Query) AddSort

func (q *Query) AddSort(value string)

AddSort adds key/value pair to queries array

func (*Query) DefaultLimit

func (q *Query) DefaultLimit(n int)

DefaultLimit set default limit

func (*Query) DefaultSort

func (q *Query) DefaultSort(s string)

DefaultSort set default sort column

type Relation

type Relation struct {
	Links Links
	Data  interface{}
}

Relation structure

func (Relation) MarshalJSON

func (r Relation) MarshalJSON() ([]byte, error)

MarshalJSON marshaller

type Request

type Request struct {
	Data struct {
		ID         json.Number                `json:"id"`
		Type       string                     `json:"type"`
		Attributes map[string]json.RawMessage `json:"attributes"`
	} `json:"data"`
}

Request structure for unmarshaling

type Response

type Response struct {
	Data     interface{} `json:"data,omitempty"`
	Included interface{} `json:"included,omitempty"`
	Meta     *MetaData   `json:"meta,omitempty"`
	Scope    string      `json:"-"`
	Errors
}

Response structure for json api response

func (*Response) MarshalJSON

func (r *Response) MarshalJSON() ([]byte, error)

MarshalJSON marshaller

type Unmarshaler

type Unmarshaler interface {
	UnmarshalJSONAPI([]byte) error
}

Unmarshaler interface

type Validator

type Validator struct {
	Errors
}

Validator structure

func (*Validator) Float32

func (v *Validator) Float32(value float32, pointer string, min, max float32)

Float32 validates int min, max. -1 for any

v.Float32(Float32Value, "number", -1, 11)  // max 18

func (*Validator) Float64

func (v *Validator) Float64(value float64, pointer string, min, max float64)

Float64 validates int min, max. -1 for any

v.Float64(Float64Value, "number", -1, 11)  // max 18

func (*Validator) Format

func (v *Validator) Format(value, pointer, reg string)

Format validates string format with regex string

v.Format(StringValue,"ip address", `\A(\d{1,3}\.){3}\d{1,3}\z`)

func (*Validator) Int

func (v *Validator) Int(value int, pointer string, min, max int)

Int validates int min, max. -1 for any

v.Int(IntValue, "number", -1, 11)  // max 18

func (*Validator) Int64

func (v *Validator) Int64(value int64, pointer string, min, max int64)

Int64 validates int min, max. -1 for any

v.Int64(Int64Value, "number", -1, 11)  // max 18

func (*Validator) Int64Present

func (v *Validator) Int64Present(value int64, pointer string)

Int64Present validates if value is not 0

v.Int64Present(Int64Value, "number")

func (*Validator) Present

func (v *Validator) Present(value, pointer string)

Present validates string for presence

v.Present(SomeVariable, "name")

func (*Validator) StringLength

func (v *Validator) StringLength(value, pointer string, min, max int)

StringLength validates string min, max length. -1 for any

v.StringLength(SomeVariable, "password", 6, 18) // min 6, max 18

func (*Validator) Uint64

func (v *Validator) Uint64(value uint64, pointer string, min, max int)

Uint64 validates int min, max. -1 for any

v.Uint64(Uint64Value, "number", -1, 11)  // max 18

func (*Validator) Uint64Present

func (v *Validator) Uint64Present(value uint64, pointer string)

Uint64Present validates if value is not 0

v.Uint64Present(Uint64Value, "number")

func (Validator) Verify

func (v Validator) Verify() error

Verify returns error if errors present and nil if empty

Jump to

Keyboard shortcuts

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