Created
August 24, 2018 16:30
-
-
Save defp/a75de1eceef52f5b50559d9287169962 to your computer and use it in GitHub Desktop.
RoundTripper demo
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
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"log" | |
"math/rand" | |
"net/http" | |
"strings" | |
"time" | |
) | |
type sleepTransport struct { | |
maxSecond int | |
originalTransport http.RoundTripper | |
} | |
func (c *sleepTransport) RoundTrip(r *http.Request) (*http.Response, error) { | |
rand.Seed(time.Now().Unix()) | |
n := rand.Intn(c.maxSecond) | |
log.Println("sleep second is ", n) | |
time.Sleep(time.Duration(n) * time.Second) | |
resp, err := c.originalTransport.RoundTrip(r) | |
if err != nil { | |
return nil, err | |
} | |
return resp, nil | |
} | |
func main() { | |
client := &http.Client{ | |
Transport: &sleepTransport{ | |
maxSecond: 20, | |
originalTransport: http.DefaultTransport, | |
}, | |
Timeout: time.Second * 20, | |
} | |
req, err := http.NewRequest(http.MethodGet, "http://localhost:8000", strings.NewReader("")) | |
if err != nil { | |
log.Fatalf("An error occurred ... %v", err) | |
} | |
resp, err := client.Do(req) | |
if err != nil { | |
log.Fatalf("An error occurred ... %v", err) | |
} | |
buf, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
log.Fatalf("An error occurred ... %v", err) | |
} | |
fmt.Printf("The body of the response is \"%s\" \n\n", string(buf)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment