github.com/puellanivis/breton@v0.2.16/lib/files/httpfiles/json.go (about)

     1  package httpfiles
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/puellanivis/breton/lib/files"
     7  	"github.com/puellanivis/breton/lib/files/json"
     8  )
     9  
    10  // REST is a convenience function, that marshals the send parameter into JSON, uses it as an attached content to read the uri, and then unmarshals the JSON received into the recv parameter.
    11  func REST(ctx context.Context, uri string, send, recv interface{}) error {
    12  	r, err := files.Open(ctx, uri, WithJSON(send))
    13  	if err != nil {
    14  		return err
    15  	}
    16  
    17  	return json.ReadFrom(r, recv)
    18  }
    19  
    20  // WithJSON takes a value which is marshalled to JSON, and then attached to a Context, which is then used as the POST body in this library.
    21  func WithJSON(v interface{}, opts ...json.Option) files.Option {
    22  	return func(f files.File) (files.Option, error) {
    23  		b, err := json.Marshal(v, opts...)
    24  		if err != nil {
    25  			return nil, err
    26  		}
    27  
    28  		return WithContent("POST", "application/json", b)(f)
    29  	}
    30  }