codec

package
v0.0.0-...-a6b2323 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2025 License: MIT Imports: 3 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EncodeError

func EncodeError(f func(http.ResponseWriter, error) error) func(c *codec)

func WithDecode

func WithDecode(decodeFunc func(*http.Request, any) error) func(c *codec)

func WithEncode

func WithEncode(f func(http.ResponseWriter, any) error) func(c *codec)

func WithPathDecode

func WithPathDecode(f func(req *http.Request, name string, val any) error) func(c *codec)

func WithQueryDecode

func WithQueryDecode(f func(*http.Request, any) error) func(c *codec)

Types

type CodeCOption

type CodeCOption func(c *codec)

type Codec

type Codec interface {
	// Decode parses the request body into the specified value.
	// Example:
	//	type User struct {
	//		Name string `json:"name"`
	//		Age  int    `json:"age"`
	//	}
	//	var user User
	//	err := codec.decode(req, &user)
	//	if err != nil {
	//		// Handle error
	//	}
	Decode(req *http.Request, val any) error

	// DecodePath decodes the `name` parameter from the request path.
	// The `val` type must be a pointer to a string or a number.
	// Example:
	// For a request: /api/v1/users/{id}
	//	var id int
	//	err := codec.decodePath(req, "id", &id)
	//	if err != nil {
	//		// Handle error
	//	}
	//	fmt.Println("Decoded ID:", id)
	DecodePath(req *http.Request, name string, val any) error

	// DecodeQuery parses the query parameters from the URL into the specified value.
	// Example:
	//	type Filter struct {
	//		Page int    `query:"page"`
	//		Sort string `query:"sort"`
	//	}
	//	var filter Filter
	//	err := codec.DecodeQuery(req, &filter)
	//	if err != nil {
	//		// Handle error
	//	}
	//	fmt.Println("Filter:", filter)
	DecodeQuery(*http.Request, any) error

	// DecodeHeader parses the query parameters from the URL into the specified value.
	// Example:
	//	type ApiToken struct {
	//		Key int    `header:"X-API-TOKEN"`
	//	}
	//	err := codec.DecodeHeader(req, &filter)
	//	if err != nil {
	//		// Handle error
	//	}
	//	fmt.Println("Filter:", filter)
	DecodeHeader(*http.Request, any) error

	// Encode serializes the specified value and writes it to the response body.
	// Example:
	//	data := map[string]string{"status": "success"}
	//	err := codec.encode(w, data)
	//	if err != nil {
	//		// Handle error
	//	}
	Encode(http.ResponseWriter, any) error

	// EncodeError serializes the error and writes it to the response body.
	// Example:
	//	err := errors.New("something went wrong")
	//	codec.encodeError(w, err)
	EncodeError(http.ResponseWriter, error) error
}

func New

func New(opts ...CodeCOption) Codec

Jump to

Keyboard shortcuts

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