Skip to content

Instantly share code, notes, and snippets.

@koolay
Created March 20, 2019 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koolay/9ac5714fd1c525b92d4fc51846b7fdc5 to your computer and use it in GitHub Desktop.
Save koolay/9ac5714fd1c525b92d4fc51846b7fdc5 to your computer and use it in GitHub Desktop.
cocurrency http client example for golang
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gojektech/heimdall/httpclient"
)
func main() {
// Create a new HTTP client with a default timeout
timeout := 5000 * time.Millisecond
client := httpclient.NewClient(httpclient.WithHTTPTimeout(timeout))
headers := http.Header{}
headers.Set("Authorization", "Bearer xxx")
headers.Set("Content-Type", "application/json")
payload := `
{}
`
url := "https://localhost/api/users"
var mu sync.WaitGroup
st := time.Now()
var syncTotal int64
for i := 0; i < 40; i++ {
go func() {
mu.Add(1)
defer mu.Done()
sst := time.Now()
// Use the clients GET method to create and execute the request
res, err := client.Post(url, strings.NewReader(payload), headers)
if err != nil {
panic(err)
}
defer res.Body.Close()
_, err = ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
fmt.Println(res.Status)
curDuration := time.Now().Sub(sst).Nanoseconds()
atomic.AddInt64(&syncTotal, curDuration)
}()
}
mu.Wait()
fmt.Println("total: ", time.Now().Sub(st).Nanoseconds())
fmt.Println("syncTotal: ", atomic.LoadInt64(&syncTotal))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment