Handling HTTP Requests and Responses in Go
Examples of Handling HTTP Requests and Responses in Go
When developing web applications in Go, understanding how to handle HTTP requests and responses is essential. This capability allows developers to create robust APIs and serve dynamic content. Below are three diverse examples demonstrating different scenarios for handling HTTP requests and responses in Go.
Example 1: Basic GET Request Handler
Context
This example illustrates a simple HTTP server that responds to GET requests. This is a foundational use case for serving static content or data.
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/hello", helloHandler)
http.ListenAndServe(":8080", nil)
}
Notes
- To test this example, run the server and navigate to
http://localhost:8080/helloin your browser. - The response will be a simple text message, demonstrating how to set the content type and write to the response body.
Example 2: Handling JSON Data with POST Requests
Context
In this example, we create an HTTP server that handles POST requests and processes JSON data. This is commonly used in RESTful APIs.
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
func userHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}
var user User
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&user); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
response := fmt.Sprintf("Received user: %s with email: %s", user.Name, user.Email)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"message": response})
}
func main() {
http.HandleFunc("/user", userHandler)
http.ListenAndServe(":8080", nil)
}
Notes
- To test this example, send a POST request to
http://localhost:8080/userwith a JSON body like{ "name": "John", "email": "john@example.com" }. - The server will respond with a JSON message confirming the received user data.
Example 3: Error Handling and Custom Responses
Context
This example demonstrates how to handle errors gracefully and provide custom responses based on the HTTP request status. This can enhance user experience by giving clear feedback.
package main
import (
"fmt"
"net/http"
)
func errorHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Page not found", http.StatusNotFound)
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
errorHandler(w, r)
return
}
fmt.Fprintf(w, "Welcome to the Home Page!")
})
http.ListenAndServe(":8080", nil)
}
Notes
- In this example, if a user navigates to any path other than the root, they will receive a 404 error message.
- This is a simple method for managing error responses, making your application more user-friendly.
These examples provide a solid foundation for handling HTTP requests and responses in Go. By understanding these patterns, developers can build more complex and interactive web applications.
Related Topics
Explore More Go Code Snippets
Discover more examples and insights in this category.
View All Go Code Snippets