Terminating HTTP Requests in Go
In Go, you can terminate an HTTP request by returning from the ServeHTTP() method of an HTTP handler. This approach allows you to end the request and send a response to the client.
Example:
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 })
Notes:
Example:
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 })
Example:
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 })
Propagation of Errors:
If you encounter an error outside of ServeHTTP(), you must return that error state so that ServeHTTP() can terminate the request.
Example:
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 })
The above is the detailed content of How to Effectively Terminate HTTP Requests in Go?. For more information, please follow other related articles on the PHP Chinese website!