http.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package http
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "io"
  6. "net"
  7. "net/http"
  8. URL "net/url"
  9. "runtime"
  10. "strings"
  11. "time"
  12. "github.com/metacubex/mihomo/component/ca"
  13. C "github.com/metacubex/mihomo/constant"
  14. "github.com/metacubex/mihomo/listener/inner"
  15. )
  16. func HttpRequest(ctx context.Context, url, method string, header map[string][]string, body io.Reader) (*http.Response, error) {
  17. return HttpRequestWithProxy(ctx, url, method, header, body, "")
  18. }
  19. func HttpRequestWithProxy(ctx context.Context, url, method string, header map[string][]string, body io.Reader, specialProxy string) (*http.Response, error) {
  20. method = strings.ToUpper(method)
  21. urlRes, err := URL.Parse(url)
  22. if err != nil {
  23. return nil, err
  24. }
  25. req, err := http.NewRequest(method, urlRes.String(), body)
  26. for k, v := range header {
  27. for _, v := range v {
  28. req.Header.Add(k, v)
  29. }
  30. }
  31. if _, ok := header["User-Agent"]; !ok {
  32. req.Header.Set("User-Agent", C.UA)
  33. }
  34. if err != nil {
  35. return nil, err
  36. }
  37. if user := urlRes.User; user != nil {
  38. password, _ := user.Password()
  39. req.SetBasicAuth(user.Username(), password)
  40. }
  41. req = req.WithContext(ctx)
  42. transport := &http.Transport{
  43. // from http.DefaultTransport
  44. DisableKeepAlives: runtime.GOOS == "android",
  45. MaxIdleConns: 100,
  46. IdleConnTimeout: 30 * time.Second,
  47. TLSHandshakeTimeout: 10 * time.Second,
  48. ExpectContinueTimeout: 1 * time.Second,
  49. DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
  50. if conn, err := inner.HandleTcp(address, specialProxy); err == nil {
  51. return conn, nil
  52. } else {
  53. d := net.Dialer{}
  54. return d.DialContext(ctx, network, address)
  55. }
  56. },
  57. TLSClientConfig: ca.GetGlobalTLSConfig(&tls.Config{}),
  58. }
  59. client := http.Client{Transport: transport}
  60. return client.Do(req)
  61. }