Last active
January 21, 2021 02:43
-
-
Save fulldump/43859e14fed398b66293e82e215ddfb5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| timeout := time.Duration(5 * time.Second) | |
| client := http.Client{ | |
| Timeout: timeout, | |
| } | |
| client.Get(url) | |
| /////////////////////////////////////////////////////// | |
| var timeout = time.Duration(2 * time.Second) | |
| func dialTimeout(network, addr string) (net.Conn, error) { | |
| return net.DialTimeout(network, addr, timeout) | |
| } | |
| func main() { | |
| transport := http.Transport{ | |
| Dial: dialTimeout, | |
| } | |
| client := http.Client{ | |
| Transport: &transport, | |
| } | |
| resp, err := client.Get("http://some.url") | |
| } | |
| ///////////////////////////////////////////////////////////////// | |
| package httpclient | |
| import ( | |
| "net" | |
| "net/http" | |
| "time" | |
| ) | |
| func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) { | |
| return func(netw, addr string) (net.Conn, error) { | |
| conn, err := net.DialTimeout(netw, addr, cTimeout) | |
| if err != nil { | |
| return nil, err | |
| } | |
| conn.SetDeadline(time.Now().Add(rwTimeout)) | |
| return conn, nil | |
| } | |
| } | |
| func NewTimeoutClient(connectTimeout time.Duration, readWriteTimeout time.Duration) *http.Client { | |
| return &http.Client{ | |
| Transport: &http.Transport{ | |
| Dial: TimeoutDialer(connectTimeout, readWriteTimeout), | |
| }, | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment