跳过SSL验证

  1. import (
  2. "crypto/tls"
  3. "net/http"
  4. "net/http/cookiejar"
  5. )
  6. ...
  7. //跳过证书验证
  8. tr := &http.Transport{
  9. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  10. }
  11. //http cookie接口
  12. cookieJar, _ := cookiejar.New(nil)
  13. c := &http.Client{
  14. Jar: cookieJar,
  15. Transport: tr,
  16. }
  17. c.Get("https://192.168.0.199:8443/config/app: ")

上传文件

  1. // httpUpload 通过 HTTP 上传文件
  2. func httpUpload(c *http.Client, filePth string) error {
  3. // 设置超时时间,并在完成任务后重置此时间
  4. defaultTimeout := c.Timeout
  5. c.Timeout = 8 * time.Minute
  6. defer func() { c.Timeout = defaultTimeout }()
  7. var (
  8. rawURL = "http://x.x.x.x/uplaod"
  9. formFieldName = "filename"
  10. params = url.Values{
  11. "reset_rwfs": []string{"on"},
  12. "FileName_Image": []string{"xxx"},
  13. }
  14. )
  15. // 打开文件
  16. f, err := os.OpenFile(filePth, os.O_RDONLY, 0)
  17. if err != nil {
  18. return errors.Wrap(err, "open file")
  19. }
  20. body := new(bytes.Buffer)
  21. bodyWriter := multipart.NewWriter(body)
  22. // 参数
  23. for filedName, values := range params {
  24. for _, v := range values {
  25. _ = bodyWriter.WriteField(filedName, v)
  26. }
  27. }
  28. // 上传文件的字段和文件名
  29. part, _ := bodyWriter.CreateFormFile(formFieldName, filepath.Base(filePth))
  30. if _, err := io.Copy(part, f); err != nil {
  31. return err
  32. }
  33. _ = bodyWriter.Close()
  34. req, err := http.NewRequest("POST", rawURL, body)
  35. if err != nil {
  36. return err
  37. }
  38. req.Header.Add("Content-Type", bodyWriter.FormDataContentType())
  39. // 发送请求,并等待应答
  40. resp, err := c.Do(req)
  41. if err != nil {
  42. return err
  43. }
  44. defer resp.Body.Close()
  45. respBody, err := ioutil.ReadAll(resp.Body)
  46. if err != nil {
  47. return err
  48. }
  49. //fmt.Println(string(respBody))
  50. //todo: 分析服务器的应答消息
  51. return nil
  52. }

支持gzip和br压缩

HTTP服务器通常支持gzip或br压缩内容,减少网络的负载。当请求的时候的Accept-Encoding字段带有gzip或br的话,如:

  1. r := &Requester{
  2. requestHook: onReqFunc,
  3. responseHook: onResFunc,
  4. CustomHeader: http.Header(map[string][]string{
  5. "Accept-Encoding": {"gzip", "deflate", "br"}, // br(Brotli) 是一种全新的数据压缩格式,2015年发布
  6. "User-Agent": {"Mozilla/5.0 (X11; Linux x86_64; rv:83.0) Gecko/20100101 Firefox/83.0"},
  7. }),
  8. }

这时候你的客户端收到的response是被压缩的,不能直接读取,需要先进行解压:

  1. import (
  2. "compress/gzip"
  3. "github.com/andybalholm/brotli"
  4. ...
  5. )
  6. // ...
  7. // reader, err := r.maybeAddDecompressor(res.Header.Get("Content-Encoding"), res.Body)
  8. // ...
  9. // maybeAddDecompressor 也许会给 body 添加相关的解压器,当`contentEncoding`为 gzip 或 br
  10. func (r *Requester) maybeAddDecompressor(contentEncoding string, body io.Reader) (io.Reader, error) {
  11. switch strings.ToLower(contentEncoding) {
  12. case "gzip":
  13. return gzip.NewReader(body)
  14. case "br":
  15. return brotli.NewReader(body), nil
  16. default:
  17. return body, nil
  18. }
  19. }

转换编码格式

  1. package xxx
  2. import (
  3. "golang.org/x/net/html/charset"
  4. "golang.org/x/text/encoding/unicode"
  5. "golang.org/x/text/transform"
  6. //...
  7. )
  8. // ...
  9. // if strings.Contains(strings.ToLower(resContentType), "text/html") { // 仅仅尝试对HTML页面进行编码转换
  10. // reader, err = r.maybeAddEncodingDecoder(resContentType, reader)
  11. // if err != nil {
  12. // return err
  13. // }
  14. // }
  15. // ...
  16. // determineEncoding 也许会给 body 添加相关的字符编码转换器,当内容不是UTF-8时,会将它转换成UTF-8
  17. // 先读取 body 前 1024 bytes内容,然后由 `charset.DetermineEncoding(data, contentType)` 确认编码,再决定是否进行编码转换
  18. func (r *Requester) maybeAddEncodingDecoder(contentType string, body io.Reader) (io.Reader, error) {
  19. buf := make([]byte, 1024)
  20. n, err := body.Read(buf)
  21. if err != nil {
  22. return nil, err
  23. }
  24. // 确定字符编码
  25. encode, _, _ := charset.DetermineEncoding(buf[:n], contentType)
  26. if encode != unicode.UTF8 { // 对于非 UTF-8 编码的页面,则转为 UTF-8
  27. readers := io.MultiReader(bytes.NewReader(buf[:n]), body)
  28. return transform.NewReader(readers, encode.NewDecoder()), nil
  29. }
  30. return body, nil
  31. }