2017-07-10 98 views
0

我正在嘗試使用Go例程將Json數據返回給請求。當我test1(w,r)沒有「去」我的代碼工作。當我使用test1()作爲去例行程序時,我沒有收到任何json數據。這是爲什麼發生?否Json返回

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) 

} 

回答

1

根據您的代碼流,我沒有看到使用goroutine的一個要點。可能你有一些理由。

讓我們來看看你的問題。目前,您的請求在由viewdata處理程序啓動的goroutine之前完成。所以,你必須使用sync.WaitGroup來等待goutoutine test1來完成執行。

你的更新代碼:

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) 
} 
0

HTTP處理程序已經催生了爲夠程。所以你不需要產生你的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) 
}