在Go 中終止HTTP 請求
在Go 中,您可以從HTTP 處理程序的ServeHTTP() 方法返回來終止HTTP請求。這種方法允許您結束請求並向客戶端發送回應。
示例:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // Examine incoming parameters if !ok { str := `{"Result":"","Error":"No valid Var"}` fmt.Fprint(w, str) return // Terminate the request } // Continue normal API serving })
註釋:
範例:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // Examine incoming parameters if !ok { http.Error(w, `Invalid input params!`, http.StatusBadRequest) return // Terminate the request } // Continue normal API serving })
範例:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // Examine incoming parameters if !ok { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusBadRequest) str := `{"Result":"","Error":"No valid Var"}` fmt.Fprint(w, str) return // Terminate the request } // Continue normal API serving })
錯誤傳播:
如果您在外部遇到錯誤的ServeHTTP() 時,您必須傳回該錯誤狀態,以便ServeHTTP() 可以終止請求。
範例:
type params struct { // Field definitions for your parameters } func decodeParams(r *http.Request) (*params, error) { p := new(params) // Decode parameters if !ok { return nil, errors.New("Invalid params") } return p, nil } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { p, err := decodeParams(r) if err != nil { http.Error(w, `Invalid input params!`, http.StatusBadRequest) return // Terminate the request } // Continue normal API serving })
以上是Go中如何有效終止HTTP請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!