Skip to content

Instantly share code, notes, and snippets.

@lidashuang lidashuang/sleep.go
Created Aug 24, 2018

Embed
What would you like to do?
RoundTripper demo
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
You can’t perform that action at this time.