Home > other >  Is there a built-in way to respond with a HTTP message 200 and empty body?
Is there a built-in way to respond with a HTTP message 200 and empty body?

Time:10-30

I need to have a "check" HTTP endpoint that will just reply with a 200 code and empty body. The solution I have requires a separate function for that:

package main

import (
    "net/http"

    "github.com/gorilla/mux"
    "github.com/rs/zerolog/log"
)

func main() {
    r := mux.NewRouter()
    r.Use(mux.CORSMethodMiddleware(r))
    r.HandleFunc("/check", send200).Methods(http.MethodGet)
    err := http.ListenAndServe("0.0.0.0:9991", r)
    if err != nil {
        log.Panic().Msgf("cannot start web server: %v", err)
    }
}

func send200(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    _, err := w.Write([]byte{})
    if err != nil {
        log.Error().Msgf("cannot send 200 answer → %v", err)
    }
}

It works as expected:

curl -v http://localhost:9991/check
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 9991 (#0)
> GET /check HTTP/1.1
> Host: localhost:9991
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Fri, 29 Oct 2021 12:11:06 GMT
< Content-Length: 0

Is there a simpler, possibly more Golangic way to handle /check as a one-liner directly at the routing code?

CodePudding user response:

Use an empty handler (a handler function whose body is empty: {}). If you write nothing to the response writer and set no status code, HTTP 200 OK will be sent back by default.

You may also use an anonymous function (function literal):

r.HandleFunc("/check", func(http.ResponseWriter, *http.Request){}).
    Methods(http.MethodGet)

CodePudding user response:

Go does not provide a handler that responds with a 200 status and an empty response body, but that's what happens when a handler does not call any of the response writer methods.

If the handler does not call WriteHeader, then the server responds with a 200 status code. Explicit calls to WriteHeader are primarily used to send error codes.

The response body is whatever the handler writes to the response. The response is empty if the handler does not write to the response.

Use an empty function to send the 200 response with an empty body:

send200 := func(http.ResponseWriter, *http.Request) {}
r.HandleFunc("/check", send200).Methods(http.MethodGet)
  • Related