encoding

package
v0.0.0-...-5930cac Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2024 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package encoding implements data encoding and decoding used in Gear.

Index

Examples

Constants

View Source
const (
	MIME_JSON     = "application/json"
	MIME_XML      = "application/xml"
	MIME_TEXT_XML = "text/xml"
)

Variables

View Source
var EncodeJSON = func(v any, w io.Writer) error {
	return json.NewEncoder(w).Encode(v)
}

EncodeJSON writes the JSON encoding of v to the stream w.

View Source
var EncodeXML = func(v any, w io.Writer) error {
	return xml.NewEncoder(w).Encode(v)
}

EncodeXML writes the XML encoding of v to the stream w.

Functions

func DecodeBody

func DecodeBody(r *http.Request, decoder BodyDecoder, v any) (err error)

DecodeBody decodes r.Body using decoder and stores the result in the value pointed to by v. If decoder is nil, Content-Type header of r will be used to select an appropriate decoder from the built-in decoders and decoders registered by RegisterBodyDecoder. If there is no decoder for that type, UnknownMIMEError error is returned. See BodyDecoder for details.

func DecodeForm

func DecodeForm(r *http.Request, decoder MapDecoder, v any) (err error)

DecodeForm decodes r.Form using decoder and stores the result in the value pointed by v. If decoder is nil, FormDecoder will be used. Note: r.ParseForm or ParseMultipartForm should be call to populate r.Form.

func DecodeHeader

func DecodeHeader(r *http.Request, decoder MapDecoder, v any) (err error)

DecodeForm decodes r.Header using decoder and stores the result in the value pointed by v. If decoder is nil, HeaderDecoder will be used.

func DecodeQuery

func DecodeQuery(r *http.Request, decoder MapDecoder, v any) (err error)

DecodeQuery decodes r.URL.Query() using decoder and stores the result in the value pointed by v. If decoder is nil, QueryDecoder will be used.

func RegisterBodyDecoder

func RegisterBodyDecoder(mime string, decoder BodyDecoder)

RegisterBodyDecoder registers decoder for mime, previous decoder(if any) of mime will be overwritten. This package registers JSONBodyDecoder for MIME_JSON, and XMLBodyDecoder for MIME_XML and MIME_TEXT_XML in package initialization. DecodeBody selects an appropriate decoder from the registered decoders to decode the request body.

It's not safe to call RegisterBodyDecoder concurrently with DecodeBody.

Types

type BodyDecoder

type BodyDecoder interface {
	// DecodeBody parses body and stores the result in the value pointed to by v,
	// which must be an arbitrary struct, slice, or string.
	// Well-formed data that does not fit into v is discarded.
	DecodeBody(body io.Reader, v any) error
}

BodyDecoder docodes body of http request.

Example
package main

import (
	"encoding/json"
	"io"
	"net/http"

	"github.com/mkch/gear/encoding"
)

func main() {
	var r *http.Request // From somewhere else.
	// JSONBodyDecoder decodes body into JSON object.
	var JSONBodyDecoder = encoding.BodyDecoderFunc(func(body io.Reader, v any) error {
		return json.NewDecoder(body).Decode(v)
	})

	var object struct {
		Code int
		Msg  string
	}
	encoding.DecodeBody(r, JSONBodyDecoder, &object)
}
Output:

var JSONBodyDecoder BodyDecoder = BodyDecoderFunc(func(body io.Reader, v any) error {
	return json.NewDecoder(body).Decode(v)
})

JSONBodyDecoder decodes body as JSON object.

var XMLBodyDecoder BodyDecoder = BodyDecoderFunc(func(body io.Reader, v any) error {
	return xml.NewDecoder(body).Decode(v)
})

XMLBodyDecoder decodes body as XML document.

type BodyDecoderFunc

type BodyDecoderFunc func(body io.Reader, v any) error

BodyDecoderFunc is an adapter to allow the use of ordinary functions as BodyDecoder. If f is a function with the appropriate signature, BodyDecoderFunc(f) is a BodyDecoder that calls f.

func (BodyDecoderFunc) DecodeBody

func (f BodyDecoderFunc) DecodeBody(body io.Reader, v any) error

type DecodeAddressError

type DecodeAddressError struct {
	Type reflect.Type
}

An DecodeAddressError is returned by FormDecoder.DecodeMap, describing a value that is not addressable.

func (*DecodeAddressError) Error

func (err *DecodeAddressError) Error() string

type DecodeFieldError

type DecodeFieldError struct {
	Name  string
	Type  reflect.Type
	Value string
	Err   error
}

An DecodeFieldError is returned by FormDecoder.DecodeMap, describing a value that can't convert to the type of field.

func (*DecodeFieldError) Error

func (e *DecodeFieldError) Error() string

type DecodeTypeError

type DecodeTypeError struct {
	Type reflect.Type
}

An DecodeTypeError is returned by FormDecoder.DecodeMap, describing a type that can't be decoded into.

func (*DecodeTypeError) Error

func (err *DecodeTypeError) Error() string

type HTTPDate

type HTTPDate time.Time

HTTPDate is a timestamp used in HTTP headers such as IfModifiedSince, Date, Last-Modified. HTTPDate implements MapValueUnmarshaler and can be used with MapDecoder.

Example
package main

import (
	"net/http"

	"github.com/mkch/gear"
	"github.com/mkch/gear/encoding"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		type Header struct {
			IfModifiedSince encoding.HTTPDate `map:"If-Modified-Since"`
		}
		var header Header
		gear.G(r).DecodeHeader(&header)
	})
}
Output:

func (*HTTPDate) UnmarshalMapValue

func (date *HTTPDate) UnmarshalMapValue(value []string) error

UnmarshalMapValue implements MapValueUnmarshaler.

type InvalidDecodeError

type InvalidDecodeError struct {
	Type reflect.Type
}

An InvalidDecodeError describes an invalid argument passed to FormDecoder.DecodeMap(). The argument to decode must be a non-nil pointer.

func (*InvalidDecodeError) Error

func (e *InvalidDecodeError) Error() string

type MapDecoder

type MapDecoder interface {
	DecodeMap(values map[string][]string, v any) error
}

MapDecoder decodes form values, request headers etc. Commonly used with http.Request.Header, http.Request.Form or http.Request.PostForm.

DecodeMap method works like json.Unmarshal. It parses [url.Values] and stores the result in the value pointed by v. if v is nil or not a pointer, DecodeMap returns an InvalidDecodeError.

The parameter v can be one of the following types.

  • *map[string][]string : *v is a copy of values.
  • *map[string]string : *v has the same content of values but each pair only has the firs value.
  • *map[string]any : *v has the same content as above but with any value type.

or any *struct type. The struct field can be one of the following types.

  • string
  • integers(int8, int18, uint, uintptr etc).
  • floats(float32, float64).
  • Pointers or slices of the the above.
  • Type implements MapValueUnmarshaler.

A Value is converted to the type of the field, if conversion failed, an DecodeFieldError will be returned. Slices and pointers are allocated as necessary. A Slice field contains all the values of the key, non-slice field contains the first value only. A FormValueUnmarshaler decodes []string into itself.

The follow field tags can be used:

  • `map:"key_name"` : key_name is the name of the key.
  • `map:"-"` : this field is ignored.
var FormDecoder MapDecoder = defaultMapDecoder

FormDecoder is the default MapDecoder implementation to decode HTTP forms.

var HeaderDecoder MapDecoder = defaultMapDecoder

DefaultFormDecoder is the default MapDecoder implementation to decode HTTP headers.

var QueryDecoder MapDecoder = defaultMapDecoder

QueryDecoder is the default MapDecoder implementation to decode URL queries.

type MapDecoderFunc

type MapDecoderFunc func(values map[string][]string, v any) error

MapDecoderFunc is an adapter to allow the use of ordinary functions as MapDecoder. If f is a function with the appropriate signature, MapDecoderFunc(f) is a FormDecoder that calls f.

func (MapDecoderFunc) DecodeMap

func (f MapDecoderFunc) DecodeMap(values map[string][]string, v any) error

type MapValueUnmarshaler

type MapValueUnmarshaler interface {
	// UnmarshalMapValue unmarshal from value.
	// Parameter value is a non-empty slice.
	UnmarshalMapValue(value []string) error
}

MapValueUnmarshaler is the interface implemented by types that can unmarshal form []string. MapDecoder decodes a MapValueUnmarshaler value by calling it's UnmarshalMapValue() method. UnmarshalMapValue must copy the slice if it wishes to retain the data after returning.

Example
package main

import (
	"errors"
	"strings"

	"github.com/mkch/gear"
)

type Name struct {
	First string
	Last  string
}

func (n *Name) UnmarshalMapValue(values []string) error {
	if len(values) == 0 {
		return errors.New("empty slice")
	}
	parts := strings.Split(values[0], " ")
	if len(parts) != 2 {
		return errors.New("invalid name format")
	}
	n.First, n.Last = parts[0], parts[1]
	return nil
}

type Person struct {
	Name *Name `form:"name"`
	Age  int16 `form:"age"`
}

func main() {
	var g *gear.Gear // From somewhere else.
	var person Person
	g.DecodeForm(&person) // Can decode: /some/path?name=John+Smith&age=20
}
Output:

type UnknownMIMEError

type UnknownMIMEError string

UnknownMIMEError is returned by DecodeBody if there is no such BodyDecoder matching MIME of the request body.

func (UnknownMIMEError) Error

func (err UnknownMIMEError) Error() string

Jump to

Keyboard shortcuts

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