Skip to content

Instantly share code, notes, and snippets.

@mattheusv
Created August 23, 2019 01:11
Show Gist options
  • Save mattheusv/6d0df7a7108732628fc85acee169a511 to your computer and use it in GitHub Desktop.
Save mattheusv/6d0df7a7108732628fc85acee169a511 to your computer and use it in GitHub Desktop.
goroutines-requests
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"runtime"
)
type protocol struct {
Protocol string `json:"nu_protocol"`
Status string `json:"status"`
}
var (
url = "https://control-tower-test.herokuapp.com/controltower"
requests = []map[string]interface{}{
{"nu_protocol": "123456"},
{"nu_protocol": "123457"},
{"nu_protocol": "123458"},
{"nu_protocol": "123459"},
{"nu_protocol": "123410"},
{"nu_protocol": "123411"},
}
)
func request(body map[string]interface{}, ch chan protocol) {
bodyRequest := new(bytes.Buffer)
json.NewEncoder(bodyRequest).Encode(body)
log.Println("Fazendo request...")
res, err := http.Post(url, "application/json", bodyRequest)
if err != nil {
log.Println(err)
}
var p protocol
json.NewDecoder(res.Body).Decode(&p)
ch <- p
}
func main() {
goroutineRequest()
//withOutGoroutine()
}
func goroutineRequest() {
//Este é o número de threads do SO que o Go usará para executar o nosso programa. Nós precisamos
// definir isso para ver a concorrência real, caso contrário, nossas goroutines
// apenas executa sequencialmente em uma thread.
runtime.GOMAXPROCS(6)
ch := make(chan protocol)
for _, r := range requests {
go request(r, ch)
}
// Começamos as goroutines e pedimos que enviassem sua saída para ch.
// <-ch irá bloquear e aguardar que um item esteja pronto, para que possamos exibi-lo.
// Como o <-ch só aguarda um item, precisaremos usar um loop para aguardar
// para cada response ou o programa terminará cedo demais.
for range requests {
res := <-ch
log.Println("Protocolo:", res.Protocol, "Status:", res.Status)
}
}
func withOutGoroutine() {
var protocols []protocol
for _, r := range requests {
bodyRequest := new(bytes.Buffer)
json.NewEncoder(bodyRequest).Encode(r)
log.Println("Fazendo request...")
resp, err := http.Post(url, "application/json", bodyRequest)
if err != nil {
log.Fatal(err)
}
var p protocol
json.NewDecoder(resp.Body).Decode(&p)
protocols = append(protocols, p)
}
fmt.Println(protocols)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment