Request 发送HTTP请求
(method, target string, body io.Reader, opts ...Option)
| 94 | |
| 95 | // Request 发送HTTP请求 |
| 96 | func (c *HTTPClient) Request(method, target string, body io.Reader, opts ...Option) *Response { |
| 97 | // 应用额外设置 |
| 98 | c.mu.Lock() |
| 99 | options := c.options.clone() |
| 100 | c.mu.Unlock() |
| 101 | for _, o := range opts { |
| 102 | o.apply(&options) |
| 103 | } |
| 104 | |
| 105 | // 创建请求客户端 |
| 106 | client := &http.Client{ |
| 107 | Timeout: options.timeout, |
| 108 | Jar: options.cookieJar, |
| 109 | } |
| 110 | |
| 111 | if options.transport != nil { |
| 112 | client.Transport = options.transport |
| 113 | } |
| 114 | |
| 115 | // size为0时将body设为nil |
| 116 | if options.contentLength == 0 { |
| 117 | body = nil |
| 118 | } |
| 119 | |
| 120 | // 确定请求URL |
| 121 | if options.endpoint != nil { |
| 122 | targetPath, err := url.Parse(target) |
| 123 | if err != nil { |
| 124 | return &Response{Err: err} |
| 125 | } |
| 126 | |
| 127 | targetURL := *options.endpoint |
| 128 | target = targetURL.ResolveReference(targetPath).String() |
| 129 | } |
| 130 | |
| 131 | // 创建请求 |
| 132 | var ( |
| 133 | req *http.Request |
| 134 | err error |
| 135 | ) |
| 136 | start := time.Now() |
| 137 | if options.ctx != nil { |
| 138 | req, err = http.NewRequestWithContext(options.ctx, method, target, body) |
| 139 | } else { |
| 140 | req, err = http.NewRequest(method, target, body) |
| 141 | } |
| 142 | if err != nil { |
| 143 | return &Response{Err: err} |
| 144 | } |
| 145 | |
| 146 | // 添加请求相关设置 |
| 147 | if options.header != nil { |
| 148 | for k, v := range options.header { |
| 149 | req.Header.Add(k, strings.Join(v, " ")) |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | req.Header.Set("User-Agent", "Cloudreve/"+constants.BackendVersion) |
nothing calls this directly
no test coverage detected