package api import ( "context" "dypid-client/internal/config" "fmt" "io" "net/http" "net/url" "time" ) var httpClient = &http.Client{ Transport: &http.Transport{ MaxIdleConns: 500, MaxIdleConnsPerHost: 500, IdleConnTimeout: 30 * time.Minute, }, Timeout: 30 * time.Second, } var limit chan struct{} func init() { //限制同时请求数为500 limit = make(chan struct{}, 10) } // InitConn 创建连接池 func InitConn() { for i := 0; i < 200; i++ { resp, err := httpClient.Get(config.APPConfig.Url + "/api/test") if err != nil { fmt.Println(err) return } defer func() { io.Copy(io.Discard, resp.Body) resp.Body.Close() }() } } func UploadDataToServer(ctx context.Context, data string) error { limit <- struct{}{} defer func() { <-limit }() params := url.Values{} params.Set("token", config.APPConfig.Token) params.Set("data", data) //http://127.0.0.1:8080/api/data?token=123456&data=123456 request, err := http.NewRequest( "POST", config.APPConfig.Url+"/api/data?"+params.Encode(), nil, ) if err != nil { return err } request.WithContext(ctx) resp, err := httpClient.Do(request) if err != nil { return err } defer func() { io.Copy(io.Discard, resp.Body) resp.Body.Close() }() return err }