Skip to content

Instantly share code, notes, and snippets.

@pradhumnsharma
Created August 10, 2024 01:39
Show Gist options
  • Save pradhumnsharma/bf186c91afa68bd619d38f862d5a1b38 to your computer and use it in GitHub Desktop.
Save pradhumnsharma/bf186c91afa68bd619d38f862d5a1b38 to your computer and use it in GitHub Desktop.
Interview Golang: Passing data that is coming from go routines to main method
Questions: https://docs.google.com/document/d/1R_mOM1W_v-yNxRW30Yfx_pILPjAuTUWp/edit?usp=drive_link&ouid=112036395083803415170&rtpof=true&sd=true
// Below Program is for Question 1- Variant 1
package main
import (
"fmt"
"net/http"
"sync"
)
// Please update the code as per the requirement
func main() {
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go makeRequest(i, &wg)
}
wg.Wait()
}
func makeRequest(userID int, wg *sync.WaitGroup) {
defer wg.Done()
params := fmt.Sprintf("?user_id=%d", userID)
resp, err := fakeRequest("https://example.com" + params)
if err != nil {
fmt.Println("Error:", err)
}
if resp == nil {
fmt.Println("Response is nil")
return
}
fmt.Println("Response status:", resp.StatusCode)
}
func fakeRequest(_ string) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
}, nil
}
// Below Program is for Question 2
package main
import (
"fmt"
"net/http"
"sync"
)
// Please update the code as per the requirement
func main() {
responses := make([]int, 10)
ch := make(chan int, 10)
var mu sync.Mutex
for i := 0; i < 10; i++ {
go makeRequest(i, ch, responses, &mu)
}
for value := range ch {
fmt.Println(value)
}
for value := range responses {
fmt.Println("Response = ", value)
}
fmt.Println("Response at index = 5 is:", responses[5])
}
func makeRequest(userID int, ch chan int, responses []int, mu *sync.Mutex) {
params := fmt.Sprintf("?user_id=%d", userID)
resp, err := fakeRequest("https://example.com" + params)
if err != nil {
fmt.Println("Error:", err)
}
if resp == nil {
fmt.Println("Response is nil")
return
}
mu.Lock()
responses[userID] = resp.StatusCode
mu.Unlock()
ch <- resp.StatusCode
fmt.Println("Response status:", resp.StatusCode)
}
func fakeRequest(_ string) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
}, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment