Home > database >  Why golang http response writer interface does not expose status code?
Why golang http response writer interface does not expose status code?

Time:02-03

Golang Package http provides HTTP client and server implementations. But in this package there is an interface ResponseWriter. ResponseWriter interface is used by an HTTP handler to construct an HTTP response. Though it's constructing the HTTP response, but still has not functionality to get the status code of the response.

What is the reason or logic behind this?

CodePudding user response:

Though it's constructing the HTTP response, but still has not functionality to get the status code of the response.

If you're constructing the response, you're likely interested in setting the status code. You can achieve that:

w.WriteHeader(200)

CodePudding user response:

in http handler

responseWriter.WriteHeader(http.StatusOK)

may be used although it is implicitly called if response is written using other means. quoting the docs

    // If WriteHeader is not called explicitly, the first call to Write
    // will trigger an implicit WriteHeader(http.StatusOK).
    // Thus explicit calls to WriteHeader are mainly used to
    // send error codes or 1xx informational responses.

in case of http request response.StatusCode may be used

sample server

package main

import (
    "fmt"
    "io"
    "net/http"
)

func main() {
    startServer()
}

func startServer() {
    fmt.Println("hello buddy!")
    http.HandleFunc("/", handler)
    err := http.ListenAndServe(":3333", nil)
    if err == http.ErrServerClosed {
        fmt.Println("server closed")
    } else if err != nil {
        fmt.Printf("error starting server: %s\n", err)
    }
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Println("got request. sending response")
    // w.WriteHeader(http.StatusOK)
    io.WriteString(w, "Hi ! HTTP\n")
}

sample client

func sendRequest() {
    r, err := http.Get("https://google.com")
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(r.StatusCode)
    }
}

  • Related