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

     1  package text
     2  
     3  import (
     4  	"encoding"
     5  	"fmt"
     6  	"strconv"
     7  
     8  	"github.com/abemedia/go-don"
     9  	"github.com/abemedia/go-don/internal/byteconv"
    10  	"github.com/valyala/fasthttp"
    11  )
    12  
    13  //nolint:cyclop,funlen
    14  func encode(ctx *fasthttp.RequestCtx, v any) error {
    15  	if v == nil {
    16  		return nil
    17  	}
    18  
    19  	var (
    20  		b   []byte
    21  		err error
    22  	)
    23  
    24  	switch v := v.(type) {
    25  	case string:
    26  		b = byteconv.Atob(v)
    27  	case []byte:
    28  		b = v
    29  	case int:
    30  		b = strconv.AppendInt(ctx.Response.Body(), int64(v), 10)
    31  	case int8:
    32  		b = strconv.AppendInt(ctx.Response.Body(), int64(v), 10)
    33  	case int16:
    34  		b = strconv.AppendInt(ctx.Response.Body(), int64(v), 10)
    35  	case int32:
    36  		b = strconv.AppendInt(ctx.Response.Body(), int64(v), 10)
    37  	case int64:
    38  		b = strconv.AppendInt(ctx.Response.Body(), v, 10)
    39  	case uint:
    40  		b = strconv.AppendUint(ctx.Response.Body(), uint64(v), 10)
    41  	case uint8:
    42  		b = strconv.AppendUint(ctx.Response.Body(), uint64(v), 10)
    43  	case uint16:
    44  		b = strconv.AppendUint(ctx.Response.Body(), uint64(v), 10)
    45  	case uint32:
    46  		b = strconv.AppendUint(ctx.Response.Body(), uint64(v), 10)
    47  	case uint64:
    48  		b = strconv.AppendUint(ctx.Response.Body(), v, 10)
    49  	case float32:
    50  		b = strconv.AppendFloat(ctx.Response.Body(), float64(v), 'f', -1, 32)
    51  	case float64:
    52  		b = strconv.AppendFloat(ctx.Response.Body(), v, 'f', -1, 64)
    53  	case bool:
    54  		b = strconv.AppendBool(ctx.Response.Body(), v)
    55  	case encoding.TextMarshaler:
    56  		b, err = v.MarshalText()
    57  	case error:
    58  		b = byteconv.Atob(v.Error())
    59  	case fmt.Stringer:
    60  		b = byteconv.Atob(v.String())
    61  	default:
    62  		return don.ErrNotAcceptable
    63  	}
    64  
    65  	if err != nil {
    66  		return err
    67  	}
    68  
    69  	if len(b) > 0 {
    70  		ctx.Response.SetBodyRaw(b)
    71  	}
    72  
    73  	return nil
    74  }