Skip to content

Instantly share code, notes, and snippets.

@FernandoCelmer
Created March 5, 2024 02:38
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 FernandoCelmer/da33ece55f728ca7bf80e942c67050c2 to your computer and use it in GitHub Desktop.
Save FernandoCelmer/da33ece55f728ca7bf80e942c67050c2 to your computer and use it in GitHub Desktop.
goroutines.go
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
)
const (
URL_USERS = "https://gorest.co.in/public/v2/users"
URL_USER = "https://gorest.co.in/public/v2/users/%d"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Gender string `json:"gender"`
Status string `json:"status"`
}
type Request interface {
Get(url string) ([]uint8, error)
}
type web struct {
client http.Client
}
func NewRequest() Request {
client := http.Client{}
return &web{client}
}
func (web *web) Get(url string) ([]uint8, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Println(err)
return nil, err
}
res, err := web.client.Do(req)
if err != nil {
fmt.Println(err)
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return nil, err
}
return body, nil
}
func main() {
var user User
var users []User
var waitGroup sync.WaitGroup
request := NewRequest()
body, _ := request.Get(URL_USERS)
json.Unmarshal(body, &users)
lenUsers := len(users)
requestsChannel := make(chan User, lenUsers)
waitGroup.Add(lenUsers)
handler := func(id int, channel chan User, wg *sync.WaitGroup) {
defer wg.Done()
body, _ := request.Get(fmt.Sprintf(URL_USER, id))
json.Unmarshal(body, &user)
channel <- user
}
for _, user_temp := range users {
go handler(user_temp.ID, requestsChannel, &waitGroup)
}
waitGroup.Wait()
for _, item := range users {
fmt.Println(item)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment