go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/r2/opt_body.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package r2
     9  
    10  import (
    11  	"bytes"
    12  	"encoding/gob"
    13  	"encoding/json"
    14  	"io"
    15  	"net/http"
    16  )
    17  
    18  // OptBody sets a body on a context from bytes.
    19  func OptBody(body []byte) Option {
    20  	return func(r *Request) error {
    21  		r.req.ContentLength = int64(len(body))
    22  		r.req.Body = io.NopCloser(bytes.NewReader(body))
    23  		r.req.GetBody = func() (io.ReadCloser, error) {
    24  			return io.NopCloser(bytes.NewReader(body)), nil
    25  		}
    26  		r.req.ContentLength = int64(len(body))
    27  		return nil
    28  	}
    29  }
    30  
    31  // OptBodyReader sets the post body on the request.
    32  func OptBodyReader(contents io.ReadCloser) Option {
    33  	return func(r *Request) error {
    34  		r.req.Body = contents
    35  		return nil
    36  	}
    37  }
    38  
    39  // OptBodyJSON sets the post body on the request to a given
    40  // value encoded with json.
    41  func OptBodyJSON(obj interface{}) Option {
    42  	return func(r *Request) error {
    43  		contents, err := json.Marshal(obj)
    44  		if err != nil {
    45  			return err
    46  		}
    47  		r.req.Body = io.NopCloser(bytes.NewReader(contents))
    48  		r.req.GetBody = func() (io.ReadCloser, error) {
    49  			r := bytes.NewReader(contents)
    50  			return io.NopCloser(r), nil
    51  		}
    52  		r.req.ContentLength = int64(len(contents))
    53  		if r.req.Header == nil {
    54  			r.req.Header = make(http.Header)
    55  		}
    56  		r.req.Header.Set("Content-Type", "application/json; charset=utf-8")
    57  		return nil
    58  	}
    59  }
    60  
    61  // OptBodyGob sets the post body on the request to a given
    62  // value encoded with gob.
    63  func OptBodyGob(obj interface{}) Option {
    64  	return func(r *Request) error {
    65  		contents := new(bytes.Buffer)
    66  		err := gob.NewEncoder(contents).Encode(obj)
    67  		if err != nil {
    68  			return err
    69  		}
    70  		r.req.Body = io.NopCloser(contents)
    71  		r.req.GetBody = func() (io.ReadCloser, error) {
    72  			return io.NopCloser(contents), nil
    73  		}
    74  		r.req.ContentLength = int64(contents.Len())
    75  		if r.req.Header == nil {
    76  			r.req.Header = make(http.Header)
    77  		}
    78  		r.req.Header.Set("Content-Type", "application/gob")
    79  		return nil
    80  	}
    81  }