2017-07-10 11 views
0

Goルーチンを使用してJsonデータをリクエストに戻そうとしています。私がtest1(w、r)を "go"せずに実行すると、私のコードが動作します。私がgo1ルーチンとしてtest1()を使うと、jsonのデータは返されません。なぜこうなった?No Json returned

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ハンドラによって開始されたゴルーチンの前に完了します。だから、ゴルーチンtest1が実行を完了するのを待つのにsync.WaitGroupを使わなければなりません。

あなたの更新コード:

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ハンドラが既にゴルーチンとして起動されます。だから、あなたのゴルーチンを産む必要はありません。

func viewdata(w http.ResponseWriter, r *http.Request) { 
    ll := sample{ 
     "city", 
     12, 
    } 
    w.Header().Set("Content-Type", "application/json") 
    w.NewEncoder(w).Encode(ll) 
}