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

     1  package httpfiles
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"io/ioutil"
     7  	"net/http"
     8  	"net/url"
     9  )
    10  
    11  type request struct {
    12  	name string
    13  
    14  	// this is what we really care about
    15  	body []byte
    16  	req  *http.Request
    17  }
    18  
    19  func newHTTPRequest(method string, uri *url.URL) *http.Request {
    20  	return &http.Request{
    21  		Method:     method,
    22  		URL:        uri,
    23  		Proto:      "HTTP/1.1",
    24  		ProtoMajor: 1,
    25  		ProtoMinor: 1,
    26  		Header:     make(http.Header),
    27  		Host:       uri.Host,
    28  	}
    29  }
    30  
    31  func (r *request) Name() string {
    32  	return r.name
    33  }
    34  
    35  func (r *request) SetMethod(method string) string {
    36  	save := r.req.Method
    37  	r.req.Method = method
    38  
    39  	return save
    40  }
    41  
    42  func (r *request) SetContentType(contentType string) string {
    43  	if r.req.Header == nil {
    44  		r.req.Header = make(http.Header)
    45  	}
    46  
    47  	save := r.req.Header.Get("Content-Type")
    48  	r.req.Header.Set("Content-Type", contentType)
    49  
    50  	return save
    51  }
    52  
    53  func (r *request) SetBody(body []byte) []byte {
    54  	save := r.body
    55  	r.body = body
    56  
    57  	r.req.Method = http.MethodPost
    58  	r.req.ContentLength = int64(len(r.body))
    59  
    60  	r.req.GetBody = func() (io.ReadCloser, error) {
    61  		if len(r.body) < 1 {
    62  			return nil, nil
    63  		}
    64  
    65  		return ioutil.NopCloser(bytes.NewReader(r.body)), nil
    66  	}
    67  
    68  	// we know this http.Request.GetBody won’t throw an error
    69  	r.req.Body, _ = r.req.GetBody()
    70  
    71  	return save
    72  }