2016-08-29 52 views
1

對於傳入的HTTP請求,我必須以202 Accepted狀態碼作爲響應,同時繼續在後臺處理有效負載。例如目的,這是我目前在做什麼:如何正確關閉請求並在後臺繼續處理請求

package main 

import (
    "fmt" 
    "log" 
    "net/http" 
    "time" 

    "github.com/nbari/violetear" 
) 

func sleep() { 
    time.Sleep(3 * time.Second) 
    fmt.Println("done...") 
} 

func index(w http.ResponseWriter, r *http.Request) { 
    w.WriteHeader(http.StatusAccepted) 
    go sleep() 
} 

func main() { 
    router := violetear.New() 
    router.HandleFunc("*", index) 

    http.Handle("/", router) 
    log.Fatal(http.ListenAndServe(":8080", router)) 
} 

基本上,在處理我只是用WriteHeader和以後調用的sleep功能夠程內:

func index(w http.ResponseWriter, r *http.Request) { 
    w.WriteHeader(http.StatusAccepted) 
    go sleep() 
} 

在情況下我也喜歡回答「200 OK」,我注意到我可以簡單回報,例如:

func index(w http.ResponseWriter, r *http.Request) { 
    go sleep() 
    return 
} 

因此想知道如果我應該總是回來我想關閉:

func index(w http.ResponseWriter, r *http.Request) { 
    w.WriteHeader(http.StatusAccepted) 
    go sleep() 
    return 
} 

或者通過只寫標題,然後調用goroutine就足夠了。

回答

0

從處理程序返回是足夠的,應該做什麼。從http.Handler引用:

該請求完成

返回信號;在完成ServeHTTP調用之後或同時完成使用ResponseWriter或從Request.Body中讀取是無效的。

請注意,最後return聲明是沒有必要的,你可以簡單地省略它。當處理程序的最後一條語句被執行時,執行程序從處理程序返回,執行程序不會等待從該函數啓動的goroutines程序完成。 (請注意,deferred語句將在此之前執行,但您在此處沒有任何內容。)

此外,如果未返回HTTP標頭,則會自動設置200 OK。所以,如果你想202 Accepted,以下是必需的最少:

func index(w http.ResponseWriter, r *http.Request) { 
    w.WriteHeader(http.StatusAccepted) 
    go sleep() 
} 

只要確保你的,因爲他們可以重複使用處理程序返回後,您不使用http.ResponseWriterhttpRequest值併發的goroutine,所以你甚至不應該嘗試閱讀它們。