Categorygithub.com/mishudark/magic
modulepackage
0.0.0-20200508153917-1a13751f1a5a
Repository: https://github.com/mishudark/magic.git
Documentation: pkg.go.dev

# README

magic-decoder

This lib makes your http decoders "magic"

install

go get -u github.com/mishudark/magic-decoder

Usage

Define the struct as usual, path and form tags are available, to decode fields from query params, and router, this will convert to the struct field type magically

type item struct {
    ID     int     `path:"id"`
    TeamID int     `path:"team_id"`
    SDRN   string  `form:"sdrn"`
    Amount float64 `json:"amount"`
    Name   string  `json:"name"`
}

list of decoders

JSON - "json" tag
ChiRouter - "path" tag
MuxRouter - "path" tag
QueryParams - "form" tag

Use the needed decoders with decode.Magic

func magicHandler(w http.ResponseWriter, r *http.Request) {
    var payload item

    err := magic.Decode(&payload, r,
        magic.JSON,
        magic.ChiRouter,
        magic.QueryParams,
    )

    if err != nil {
        // do something
    }
}

For sure you can create shortcuts to common tasks

func decodeGetRequest(r *http.Request, container interface{}) error {
    return decode.Decode(r, container,
        magic.ChiRouter,
        magic.QueryParams,
    )
}

func decodePostRequest(r *http.Request, container interface{}) error {
    return magic.Decode(r, container,
        magic.JSON,
        magic.ChiRouter,
    )
}

Create a custom decoder

Decoder is an abstraction to decode info from a request into a container, container always should be a pointer to a struct

type Decoder func(r *http.Request, container interface{}) error

# Functions

ChiRouter extracts fields from chi router.
Decode apply a series of decoders in the order they are it is, decoder 1,2,3 will be applied in order 1,2,3 container must be a pointer to a struct.
JSON unmarshal.
MuxRouter extracts fields from gorilla mux route.
ParseToStruct converts a map of strings to its reference on a struct, it will try to convert the data into the type defined in the struct field.
QueryParams extract fields from GET query params.

# Type aliases

Decoder is an abstraction to decode info from a request into a container container always should be a pointer to a struct.