github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/engine/access/rest/request/helpers.go (about)

     1  package request
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"io"
     8  	"strings"
     9  
    10  	"github.com/onflow/flow-go/model/flow"
    11  )
    12  
    13  func parseBody(raw io.Reader, dst interface{}) error {
    14  	dec := json.NewDecoder(raw)
    15  	dec.DisallowUnknownFields()
    16  
    17  	err := dec.Decode(&dst)
    18  	if err != nil {
    19  		var syntaxError *json.SyntaxError
    20  		var unmarshalTypeError *json.UnmarshalTypeError
    21  
    22  		switch {
    23  		case errors.As(err, &syntaxError):
    24  			return fmt.Errorf("request body contains badly-formed JSON (at position %d)", syntaxError.Offset)
    25  		case errors.Is(err, io.ErrUnexpectedEOF):
    26  			return fmt.Errorf("request body contains badly-formed JSON")
    27  		case errors.As(err, &unmarshalTypeError):
    28  			return fmt.Errorf("request body contains an invalid value for the %q field (at position %d)", unmarshalTypeError.Field, unmarshalTypeError.Offset)
    29  		case strings.HasPrefix(err.Error(), "json: unknown field "):
    30  			fieldName := strings.TrimPrefix(err.Error(), "json: unknown field ")
    31  			return fmt.Errorf("request body contains unknown field %s", fieldName)
    32  		case errors.Is(err, io.EOF):
    33  			return fmt.Errorf("request body must not be empty")
    34  		default:
    35  			return err
    36  		}
    37  	}
    38  
    39  	if dst == nil {
    40  		return fmt.Errorf("request body must not be empty")
    41  	}
    42  
    43  	err = dec.Decode(&struct{}{})
    44  	if err != io.EOF {
    45  		return fmt.Errorf("request body must only contain a single JSON object")
    46  	}
    47  
    48  	return nil
    49  }
    50  
    51  type GetByIDRequest struct {
    52  	ID flow.Identifier
    53  }
    54  
    55  func (g *GetByIDRequest) Build(r *Request) error {
    56  	return g.Parse(
    57  		r.GetVar(idQuery),
    58  	)
    59  }
    60  
    61  func (g *GetByIDRequest) Parse(rawID string) error {
    62  	var id ID
    63  	err := id.Parse(rawID)
    64  	if err != nil {
    65  		return err
    66  	}
    67  	g.ID = id.Flow()
    68  
    69  	return nil
    70  }