requests.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. package requests
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "io/ioutil"
  8. "mime/multipart"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "strings"
  13. )
  14. // Client: 封装了http的参数等信息
  15. type Client struct {
  16. // 自定义Client
  17. client *http.Client
  18. url string
  19. method string
  20. header http.Header
  21. params url.Values
  22. form url.Values
  23. json interface{}
  24. multipart FileForm
  25. }
  26. // FileForm: form参数和文件参数
  27. type FileForm struct {
  28. Value url.Values
  29. File map[string]string
  30. }
  31. // Result: http响应结果
  32. type Result struct {
  33. Resp *http.Response
  34. Err error
  35. }
  36. // Get: http `GET` 请求
  37. func Get(url string) *Client {
  38. return newClient(url, http.MethodGet, nil)
  39. }
  40. // Post: http `POST` 请求
  41. func Post(url string) *Client {
  42. return newClient(url, http.MethodPost, nil)
  43. }
  44. // Put: http `PUT` 请求
  45. func Put(url string) *Client {
  46. return newClient(url, http.MethodPut, nil)
  47. }
  48. // Delete: http `DELETE` 请求
  49. func Delete(url string) *Client {
  50. return newClient(url, http.MethodDelete, nil)
  51. }
  52. // Request: 用于自定义请求方式,比如`HEAD`、`PATCH`、`OPTIONS`、`TRACE`
  53. // client参数用于替换DefaultClient,如果为nil则会使用默认的
  54. func Request(url, method string, client *http.Client) *Client {
  55. return newClient(url, method, client)
  56. }
  57. // Params: http请求中url参数
  58. func (c *Client) Params(params url.Values) *Client {
  59. for k, v := range params {
  60. c.params[k] = v
  61. }
  62. return c
  63. }
  64. // Header: http请求头
  65. func (c *Client) Header(k, v string) *Client {
  66. c.header.Set(k, v)
  67. return c
  68. }
  69. // Headers: http请求头
  70. func (c *Client) Headers(header http.Header) *Client {
  71. for k, v := range header {
  72. c.header[k] = v
  73. }
  74. return c
  75. }
  76. // Form: 表单提交参数
  77. func (c *Client) Form(form url.Values) *Client {
  78. c.header.Set("Content-Type", "application/x-www-form-urlencoded")
  79. c.form = form
  80. return c
  81. }
  82. // Json: json提交参数
  83. func (c *Client) Json(json interface{}) *Client {
  84. c.header.Set("Content-Type", "application/json")
  85. c.json = json
  86. return c
  87. }
  88. // Multipart: form-data提交参数
  89. func (c *Client) Multipart(multipart FileForm) *Client {
  90. c.multipart = multipart
  91. return c
  92. }
  93. // Send: 发送http请求
  94. func (c *Client) Send() *Result {
  95. var result *Result
  96. if c.params != nil && len(c.params) != 0 {
  97. // 如果url中已经有query string参数,则只需要&拼接剩下的即可
  98. encoded := c.params.Encode()
  99. if strings.Index(c.url, "?") == -1 {
  100. c.url += "?" + encoded
  101. } else {
  102. c.url += "&" + encoded
  103. }
  104. }
  105. contentType := c.header.Get("Content-Type")
  106. if c.multipart.Value != nil || c.multipart.File != nil {
  107. result = c.createMultipartForm()
  108. } else if strings.HasPrefix(contentType, "application/json") {
  109. result = c.createJson()
  110. } else if strings.HasPrefix(contentType, "application/x-www-form-urlencoded") {
  111. result = c.createForm()
  112. } else {
  113. result = c.createEmptyBody()
  114. }
  115. return result
  116. }
  117. // form-data
  118. func (c *Client) createMultipartForm() *Result {
  119. var result = new(Result)
  120. body := &bytes.Buffer{}
  121. writer := multipart.NewWriter(body)
  122. for name, filename := range c.multipart.File {
  123. file, err := os.Open(filename)
  124. if err != nil {
  125. result.Err = err
  126. return result
  127. }
  128. part, err := writer.CreateFormFile(name, filename)
  129. if err != nil {
  130. result.Err = err
  131. return result
  132. }
  133. // todo 这里的io.Copy实现,会把file文件都读取到内存里面,然后当做一个buffer传给NewRequest。对于大文件来说会占用很多内存
  134. _, err = io.Copy(part, file)
  135. if err != nil {
  136. result.Err = err
  137. return result
  138. }
  139. err = file.Close()
  140. if err != nil {
  141. result.Err = err
  142. return result
  143. }
  144. }
  145. for name, values := range c.multipart.Value {
  146. for _, value := range values {
  147. _ = writer.WriteField(name, value)
  148. }
  149. }
  150. err := writer.Close()
  151. if err != nil {
  152. result.Err = err
  153. return result
  154. }
  155. req, err := http.NewRequest(c.method, c.url, body)
  156. req.Header = c.header
  157. req.Header.Set("Content-Type", writer.FormDataContentType())
  158. c.doSend(req, result)
  159. return result
  160. }
  161. // application/json
  162. func (c *Client) createJson() *Result {
  163. var result = new(Result)
  164. b, err := json.Marshal(c.json)
  165. if err != nil {
  166. result.Err = err
  167. return result
  168. }
  169. req, err := http.NewRequest(c.method, c.url, bytes.NewReader(b))
  170. if err != nil {
  171. result.Err = err
  172. return result
  173. }
  174. req.Header = c.header
  175. c.doSend(req, result)
  176. return result
  177. }
  178. // application/x-www-form-urlencoded
  179. func (c *Client) createForm() *Result {
  180. var result = new(Result)
  181. form := c.form.Encode()
  182. req, err := http.NewRequest(c.method, c.url, strings.NewReader(form))
  183. if err != nil {
  184. result.Err = err
  185. return result
  186. }
  187. req.Header = c.header
  188. c.doSend(req, result)
  189. return result
  190. }
  191. // none http body
  192. func (c *Client) createEmptyBody() *Result {
  193. var result = new(Result)
  194. req, err := http.NewRequest(c.method, c.url, nil)
  195. if err != nil {
  196. result.Err = err
  197. return result
  198. }
  199. req.Header = c.header
  200. c.doSend(req, result)
  201. return result
  202. }
  203. func (c *Client) doSend(req *http.Request, result *Result) {
  204. if c.client != nil {
  205. result.Resp, result.Err = c.client.Do(req)
  206. return
  207. }
  208. result.Resp, result.Err = http.DefaultClient.Do(req)
  209. }
  210. // StatusOk: 判断http响应码是否为200
  211. func (r *Result) StatusOk() *Result {
  212. if r.Err != nil {
  213. return r
  214. }
  215. if r.Resp.StatusCode != http.StatusOK {
  216. r.Err = errors.New("status code is not 200")
  217. return r
  218. }
  219. return r
  220. }
  221. // Status2xx: 判断http响应码是否为2xx
  222. func (r *Result) Status2xx() *Result {
  223. if r.Err != nil {
  224. return r
  225. }
  226. if r.Resp.StatusCode < http.StatusOK || r.Resp.StatusCode >= http.StatusMultipleChoices {
  227. r.Err = errors.New("status code is not match [200, 300)")
  228. return r
  229. }
  230. return r
  231. }
  232. // Raw: 获取http响应内容,返回字节数组
  233. func (r *Result) Raw() ([]byte, error) {
  234. if r.Err != nil {
  235. return nil, r.Err
  236. }
  237. b, err := ioutil.ReadAll(r.Resp.Body)
  238. if err != nil {
  239. r.Err = err
  240. return nil, r.Err
  241. }
  242. defer r.Resp.Body.Close()
  243. return b, r.Err
  244. }
  245. // Text: 获取http响应内容,返回字符串
  246. func (r *Result) Text() (string, error) {
  247. b, err := r.Raw()
  248. if err != nil {
  249. r.Err = err
  250. return "", r.Err
  251. }
  252. return string(b), nil
  253. }
  254. // Json: 获取http响应内容,返回json
  255. func (r *Result) Json(v interface{}) error {
  256. b, err := r.Raw()
  257. if err != nil {
  258. r.Err = err
  259. return r.Err
  260. }
  261. return json.Unmarshal(b, v)
  262. }
  263. // Save: 获取http响应内容,保存为文件
  264. func (r *Result) Save(name string) error {
  265. if r.Err != nil {
  266. return r.Err
  267. }
  268. f, err := os.Create(name)
  269. if err != nil {
  270. r.Err = err
  271. return r.Err
  272. }
  273. defer f.Close()
  274. _, err = io.Copy(f, r.Resp.Body)
  275. if err != nil {
  276. r.Err = err
  277. return r.Err
  278. }
  279. defer r.Resp.Body.Close()
  280. return nil
  281. }
  282. func newClient(u string, method string, client *http.Client) *Client {
  283. return &Client{
  284. client: client,
  285. url: u,
  286. method: method,
  287. header: make(http.Header),
  288. params: make(url.Values),
  289. form: make(url.Values),
  290. }
  291. }