github.com/binbinly/pkg@v0.0.11-0.20240321014439-f4fbf666eb0f/client/http/client.go (about)

     1  package http
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  	"time"
     7  )
     8  
     9  // defaultTimeout default http request timeout
    10  const defaultTimeout = 10 * time.Second
    11  
    12  // httpSettings http request options
    13  type httpSettings struct {
    14  	headers map[string]string
    15  	cookies []*http.Cookie
    16  	close   bool
    17  	debug   bool
    18  	timeout time.Duration
    19  }
    20  
    21  // ClientOption HTTPOption configures how we set up the http request
    22  type ClientOption func(s *httpSettings)
    23  
    24  // WithHTTPHeader specifies the headers to http request.
    25  func WithHTTPHeader(key, value string) ClientOption {
    26  	return func(s *httpSettings) {
    27  		s.headers[key] = value
    28  	}
    29  }
    30  
    31  // WithHTTPCookies specifies the cookies to http request.
    32  func WithHTTPCookies(cookies ...*http.Cookie) ClientOption {
    33  	return func(s *httpSettings) {
    34  		s.cookies = cookies
    35  	}
    36  }
    37  
    38  // WithHTTPClose specifies close the connection after
    39  // replying to this request (for servers) or after sending this
    40  // request and reading its response (for clients).
    41  func WithHTTPClose() ClientOption {
    42  	return func(s *httpSettings) {
    43  		s.close = true
    44  	}
    45  }
    46  
    47  // WithDebug specifies debug
    48  func WithDebug() ClientOption {
    49  	return func(s *httpSettings) {
    50  		s.debug = true
    51  	}
    52  }
    53  
    54  // WithHTTPTimeout specifies the timeout to http request.
    55  func WithHTTPTimeout(timeout time.Duration) ClientOption {
    56  	return func(s *httpSettings) {
    57  		s.timeout = timeout
    58  	}
    59  }
    60  
    61  // Client 定义 http client 接口
    62  type Client interface {
    63  	// Get sends an HTTP get request
    64  	Get(ctx context.Context, reqURL string, options ...ClientOption) ([]byte, error)
    65  
    66  	// Post sends an HTTP post request
    67  	Post(ctx context.Context, reqURL string, data map[string]string, options ...ClientOption) ([]byte, error)
    68  
    69  	// PostJSON sends an HTTP post request with json
    70  	PostJSON(ctx context.Context, reqURL string, body []byte, options ...ClientOption) ([]byte, error)
    71  
    72  	// Upload sends an HTTP post request for uploading media
    73  	Upload(ctx context.Context, reqURL string, form UploadForm, options ...ClientOption) ([]byte, error)
    74  }