How to get http status code from responsewriter in golang?
- User
How to get http status code from responsewriter in golang?
- Assistant
In Go, you can get the HTTP status code from the
ResponseWriterby using theWriteHeadermethod. Here is an example:package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) fmt.Println("HTTP status code:", w.Header().Get("StatusCode")) // Print the status code } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }In the example above, the
handlerfunction sets the status code tohttp.StatusNotFoundusing theWriteHeadermethod.To get the status code, you can use the
w.Header().Get("StatusCode")method. Note thatGetretrieves the value of theStatusCodeheader, which represents the status code of the response.Please note that this method will only work if you have explicitly set the status code using
WriteHeader. If you have not set the status code explicitly, it will default tohttp.StatusOK.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.