Created
February 19, 2024 05:44
-
-
Save yhsiang/50a702652d735d2143482a72dda90125 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"crypto/tls" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"time" | |
) | |
func main() { | |
idleTime := 1 * time.Second | |
transport := &http.Transport{ | |
MaxIdleConns: 0, | |
MaxConnsPerHost: 0, | |
TLSClientConfig: &tls.Config{ | |
MinVersion: tls.VersionTLS12, | |
MaxVersion: tls.VersionTLS12, | |
CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, | |
PreferServerCipherSuites: true, | |
CipherSuites: []uint16{ | |
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, | |
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, | |
tls.TLS_RSA_WITH_AES_256_GCM_SHA384, | |
tls.TLS_RSA_WITH_AES_256_CBC_SHA, | |
}, | |
}, | |
} | |
client := &http.Client{ | |
Transport: transport, | |
} | |
fmt.Printf("Client timoeut: %+v\n", client.Timeout) | |
fmt.Printf("Idle timeout: %+v\n", transport.IdleConnTimeout) | |
for { | |
performRequest(client) | |
time.Sleep(idleTime) | |
} | |
} | |
func performRequest(client *http.Client) { | |
urlString := "https://exampl.com" | |
payloadString := "my payload" | |
err := request(client, urlString, payloadString) | |
if err != nil { | |
log.Printf("request failed: %+v", err) | |
} else { | |
log.Printf("request succeeded") | |
} | |
} | |
func request(client *http.Client, urlString, payloadString string) error { | |
payload := bytes.NewBufferString(payloadString) | |
req, err := http.NewRequest(http.MethodPost, urlString, payload) | |
if err != nil { | |
return fmt.Errorf("error creating request: %s", err) | |
} | |
resp, err := client.Do(req) | |
if err != nil { | |
return fmt.Errorf("error performing request: %s", err) | |
} | |
defer func() { | |
io.Copy(ioutil.Discard, resp.Body) | |
resp.Body.Close() | |
}() | |
if resp.StatusCode != http.StatusOK { | |
body, _ := io.ReadAll(resp.Body) | |
_ = resp.Body.Close() | |
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, body) | |
} | |
body, err := io.ReadAll(resp.Body) | |
if err != nil { | |
_ = resp.Body.Close() | |
return fmt.Errorf("error reading body: %s", err) | |
} | |
if err := resp.Body.Close(); err != nil { | |
return fmt.Errorf("error closing body: %s", err) | |
} | |
if string(body) != "ok!" { | |
return fmt.Errorf("unexpected response: %s", body) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment