github.com/abemedia/go-don@v0.2.2-0.20240329015135-be88e32bb73b/encoding/decode.go (about)

     1  package encoding
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/valyala/fasthttp"
     7  )
     8  
     9  type (
    10  	Unmarshaler        = func(data []byte, v any) error
    11  	ContextUnmarshaler = func(ctx context.Context, data []byte, v any) error
    12  	RequestParser      = func(ctx *fasthttp.RequestCtx, v any) error
    13  )
    14  
    15  type DecoderConstraint interface {
    16  	Unmarshaler | ContextUnmarshaler | RequestParser
    17  }
    18  
    19  // RegisterDecoder registers a request decoder for a given media type.
    20  func RegisterDecoder[T DecoderConstraint](dec T, mime string, aliases ...string) {
    21  	switch d := any(dec).(type) {
    22  	case Unmarshaler:
    23  		decoders[mime] = func(ctx *fasthttp.RequestCtx, v any) error {
    24  			return d(ctx.Request.Body(), v)
    25  		}
    26  
    27  	case ContextUnmarshaler:
    28  		decoders[mime] = func(ctx *fasthttp.RequestCtx, v any) error {
    29  			return d(ctx, ctx.Request.Body(), v)
    30  		}
    31  
    32  	case RequestParser:
    33  		decoders[mime] = d
    34  	}
    35  
    36  	for _, alias := range aliases {
    37  		decoders[alias] = decoders[mime]
    38  	}
    39  }
    40  
    41  // GetDecoder returns the request decoder for a given media type.
    42  func GetDecoder(mime string) RequestParser {
    43  	return decoders[mime]
    44  }
    45  
    46  var decoders = map[string]RequestParser{}