Home >Backend Development >Golang >How to Gracefully Handle and Terminate HTTP Request Processing in Go?

How to Gracefully Handle and Terminate HTTP Request Processing in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-20 19:05:17848browse

How to Gracefully Handle and Terminate HTTP Request Processing in Go?

Terminating HTTP Request Processing

When serving HTTP requests, there may be scenarios where it becomes necessary to terminate the processing and send an error response. This can be achieved by returning from the ServeHTTP() method.

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // Inspect incoming parameters
    if !IsValid(r.URL.Query()) {
        str := `{"Result":"","Error":"Invalid Parameters"}`
        fmt.Fprint(w, str)
        return
    }

    // Continue normal API processing
})

Using HTTP Error Codes

For more sophisticated error handling, it's recommended to return an appropriate HTTP error code instead of the default 200 OK.

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // Inspect incoming parameters
    if !IsValid(r.URL.Query()) {
        http.Error(w, "Invalid Parameters", http.StatusBadRequest)
        return
    }

    // Continue normal API processing
})

JSON-Formatted Error Responses

To provide a more detailed error response in JSON format:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // Inspect incoming parameters
    if !IsValid(r.URL.Query()) {
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusBadRequest)
        str := `{"Result":"","Error":"Invalid Parameters"}`
        fmt.Fprint(w, str)
        return
    }

    // Continue normal API processing
})

Propagating Errors from Nested Functions

If error handling is performed in a function called from ServeHTTP(), the error state must be returned to allow ServeHTTP() to terminate the request processing:

func decodeParams(r *http.Request) (*params, error) {
    p := new(params)
    // Decode parameters and check their validity

    if !ok {
        return nil, errors.New("Invalid Parameters")
    }

    return p, nil
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
    p, err := decodeParams(r)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    // Continue normal API processing
}

The above is the detailed content of How to Gracefully Handle and Terminate HTTP Request Processing in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn