github.com/docker/engine@v22.0.0-20211208180946-d456264580cf+incompatible/testutil/request/ops.go (about)

     1  package request
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"io"
     7  	"net/http"
     8  	"strings"
     9  )
    10  
    11  // Options defines request options, like request modifiers and which host to target
    12  type Options struct {
    13  	host             string
    14  	requestModifiers []func(*http.Request) error
    15  }
    16  
    17  // Host creates a modifier that sets the specified host as the request URL host
    18  func Host(host string) func(*Options) {
    19  	return func(o *Options) {
    20  		o.host = host
    21  	}
    22  }
    23  
    24  // With adds a request modifier to the options
    25  func With(f func(*http.Request) error) func(*Options) {
    26  	return func(o *Options) {
    27  		o.requestModifiers = append(o.requestModifiers, f)
    28  	}
    29  }
    30  
    31  // Method creates a modifier that sets the specified string as the request method
    32  func Method(method string) func(*Options) {
    33  	return With(func(req *http.Request) error {
    34  		req.Method = method
    35  		return nil
    36  	})
    37  }
    38  
    39  // RawString sets the specified string as body for the request
    40  func RawString(content string) func(*Options) {
    41  	return RawContent(io.NopCloser(strings.NewReader(content)))
    42  }
    43  
    44  // RawContent sets the specified reader as body for the request
    45  func RawContent(reader io.ReadCloser) func(*Options) {
    46  	return With(func(req *http.Request) error {
    47  		req.Body = reader
    48  		return nil
    49  	})
    50  }
    51  
    52  // ContentType sets the specified Content-Type request header
    53  func ContentType(contentType string) func(*Options) {
    54  	return With(func(req *http.Request) error {
    55  		req.Header.Set("Content-Type", contentType)
    56  		return nil
    57  	})
    58  }
    59  
    60  // JSON sets the Content-Type request header to json
    61  func JSON(o *Options) {
    62  	ContentType("application/json")(o)
    63  }
    64  
    65  // JSONBody creates a modifier that encodes the specified data to a JSON string and set it as request body. It also sets
    66  // the Content-Type header of the request.
    67  func JSONBody(data interface{}) func(*Options) {
    68  	return With(func(req *http.Request) error {
    69  		jsonData := bytes.NewBuffer(nil)
    70  		if err := json.NewEncoder(jsonData).Encode(data); err != nil {
    71  			return err
    72  		}
    73  		req.Body = io.NopCloser(jsonData)
    74  		req.Header.Set("Content-Type", "application/json")
    75  		return nil
    76  	})
    77  }