I am trying to use a Go routine to return back Json data to a request. When I test1(w,r) without the "go" my code works. When I use test1() as a go routine I dont get any json data back. Why is this happening?
func main() {
http.HandleFunc("/test", viewdata)
http.ListenAndServe(":8080", nil)
}
func viewdata(w http.ResponseWriter, r *http.Request) {
go test1(w, r)
}
func test1(w http.ResponseWriter, r *http.Request) {
// example struct
ll := sample{
"city",
12,
}
w.Header().Set("Content-Type", "application/json")
json, _ := json.Marshal(ll)
w.Write(json)
}
As per your code flow, I do not see a point of using goroutine. May you have some reason.
Let's get to your question. Currently your request gets completed before the goroutine that was started by viewdata
handler. So, you have to use sync.WaitGroup
to wait for goroutine test1
to complete the execution.
Your update code:
func viewdata(w http.ResponseWriter, r *http.Request) {
var wg sync.WaitGroup
wg.Add(1)
go test1(w, r, &wg)
wg.Wait()
}
func test1(w http.ResponseWriter, r *http.Request, wg *sync.WaitGroup) {
defer wg.Done()
ll := sample{
"city",
12,
}
w.Header().Set("Content-Type", "application/json")
json, _ := json.Marshal(ll)
w.Write(json)
}
http handler is already spawned as goroutine. So you don't need to spawn your goroutine.
func viewdata(w http.ResponseWriter, r *http.Request) {
ll := sample{
"city",
12,
}
w.Header().Set("Content-Type", "application/json")
w.NewEncoder(w).Encode(ll)
}