How do you handle HTTP responses in Go?
Example
package main
import (
"encoding/json"
"net/http"
)
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
func handler(w http.ResponseWriter, r *http.Request) {
// Create a new user object
user := User{Name: "John Doe", Email: "johndoe@example.com"}
// Marshal the user object to JSON
data, err := json.Marshal(user)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Set the Content-Type header
w.Header().Set("Content-Type", "application/json")
// Write the JSON data to the response
w.Write(data)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
In this example, we define a handler function that creates a User object, marshals it to JSON, and writes the JSON data to the response using the http.ResponseWriter interface.
We first create a new User object and marshal it to JSON using the json.Marshal function. We then set the Content-Type header to application/json using the w.Header().Set method.
Finally, we write the JSON data to the response using the w.Write method. If an error occurs during the marshaling process, we return an HTTP 500 Internal Server Error using the http.Error function.
This is just a simple example, but the http.ResponseWriter interface provides many more methods for handling HTTP responses, such as setting headers, setting cookies, and streaming data back to the client.