mihomo/component/http/http.go

71 lines
1.5 KiB
Go
Raw Normal View History

2022-06-04 19:14:39 +08:00
package http
import (
"context"
2023-09-22 14:45:34 +08:00
"crypto/tls"
2022-06-04 19:14:39 +08:00
"io"
"net"
"net/http"
URL "net/url"
2023-10-23 16:45:22 +08:00
"runtime"
2022-06-04 19:14:39 +08:00
"strings"
"time"
2023-03-25 22:56:24 +08:00
2023-09-22 14:45:34 +08:00
"github.com/Dreamacro/clash/component/ca"
C "github.com/Dreamacro/clash/constant"
2023-03-25 22:56:24 +08:00
"github.com/Dreamacro/clash/listener/inner"
2022-06-04 19:14:39 +08:00
)
func HttpRequest(ctx context.Context, url, method string, header map[string][]string, body io.Reader) (*http.Response, error) {
UA := C.UA
2022-06-04 19:14:39 +08:00
method = strings.ToUpper(method)
urlRes, err := URL.Parse(url)
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, urlRes.String(), body)
for k, v := range header {
for _, v := range v {
req.Header.Add(k, v)
}
}
if _, ok := header["User-Agent"]; !ok {
req.Header.Set("User-Agent", UA)
}
if err != nil {
return nil, err
}
if user := urlRes.User; user != nil {
password, _ := user.Password()
req.SetBasicAuth(user.Username(), password)
}
req = req.WithContext(ctx)
transport := &http.Transport{
// from http.DefaultTransport
2023-10-23 16:45:22 +08:00
DisableKeepAlives: runtime.GOOS == "android",
2022-06-04 19:14:39 +08:00
MaxIdleConns: 100,
IdleConnTimeout: 30 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
if conn, err := inner.HandleTcp(address); err == nil {
return conn, nil
} else {
d := net.Dialer{}
return d.DialContext(ctx, network, address)
}
2022-06-04 19:14:39 +08:00
},
2023-09-22 14:45:34 +08:00
TLSClientConfig: ca.GetGlobalTLSConfig(&tls.Config{}),
2022-06-04 19:14:39 +08:00
}
client := http.Client{Transport: transport}
return client.Do(req)
}