Skip to content

Instantly share code, notes, and snippets.

@sj82516
Last active March 11, 2021 23:40
Show Gist options
  • Save sj82516/6e10f70a62a1d717c78485077ff5a15d to your computer and use it in GitHub Desktop.
Save sj82516/6e10f70a62a1d717c78485077ff5a15d to your computer and use it in GitHub Desktop.
Nodejs vs Golang: http request
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type UsersResp struct {
Data []*User `json:"data"`
Limit int `json:"limit"`
}
type User struct {
Id string `json:"id"`
FirstName string `json:"firstName"`
Gender string `json:"gender"`
}
func main(){
usersClient := &http.Client{}
usersReq, _:= http.NewRequest("GET", "https://dummyapi.io/data/api/user", nil)
usersReq.Header.Add("app-id", ".....")
q := usersReq.URL.Query()
q.Add("limit", "10")
usersReq.URL.RawQuery = q.Encode()
usersResp, _ := usersClient.Do(usersReq)
body, _ := io.ReadAll(usersResp.Body)
var users UsersResp
_ = json.Unmarshal(body, &users)
ch := make(chan User)
for _, user := range users.Data{
go getUser(user, ch)
}
male := 0
female := 0
for i:=0; i<len(users.Data); i++ {
userData := <-ch
if userData.Gender == "male" {
male ++
}
if userData.Gender == "female" {
female ++
}
}
fmt.Printf("total male %v, total female %v\n", male, female)
}
var getUser = func (user *User, ch chan<- User){
userClient := &http.Client{}
userReq, _:= http.NewRequest("GET", "https://dummyapi.io/data/api/user/" + user.Id, nil)
userReq.Header.Add("app-id", "....")
userResp, _ := userClient.Do(userReq)
body, _ := io.ReadAll(userResp.Body)
var userData User
_ = json.Unmarshal(body, &userData)
ch <- userData
}
import fetch from "node-fetch"
async function main(){
const userList = await (await fetch("https://dummyapi.io/data/api/user?limit=10", {
method: "GET",
headers: {
"app-id": "..."
}
})).json()
const userDataList = await Promise.all(userList.data.map(async user => {
return await (await fetch(`https://dummyapi.io/data/api/user/${user.id}?lmit=10`, {
method: "GET",
headers: {
"app-id": "..."
}
})).json()
}))
const statics = userDataList.reduce((sum, user) => {
if(user.gender === 'male'){
sum.male ++;
}
if(user.gender === 'female'){
sum.female ++;
}
return sum
}, { male: 0, female: 0})
console.log(`total male: ${statics.male}, total female: ${statics.female}`)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment