Introduction

Handling HTTP requests is a fundamental aspect of building web applications in Go. The "net/http" package provides everything you need to create an HTTP server, define routes, and handle incoming requests. In this guide, we'll explore the key concepts of handling HTTP requests in Go and provide sample code to demonstrate the process.


The net/http Package

The "net/http" package is part of the Go standard library and offers essential components for building web servers and handling HTTP requests. It includes features for routing, middleware, and HTTP response handling.


Creating an HTTP Server

To create an HTTP server in Go, you'll need to define routes, request handlers, and start the server. Here's an example of a basic HTTP server that listens on port 8080:

package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, Go HTTP Server!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}

In this code, we create an HTTP server that listens on port 8080, registers a request handler function, and responds with "Hello, Go HTTP Server!" to all incoming requests.


Handling Different HTTP Methods

You can handle various HTTP methods (GET, POST, PUT, DELETE, etc.) by checking the request method in your handler functions. Here's an example of handling a POST request:

func postHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
// Handle the POST request here
fmt.Fprintln(w, "Received a POST request")
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func main() {
http.HandleFunc("/post", postHandler)
http.ListenAndServe(":8080", nil)
}

In this code, we define a specific handler for POST requests at the "/post" endpoint and respond accordingly.


Routing with Gorilla Mux

While the standard library's "net/http" package is sufficient for many cases, more advanced routing can be achieved using third-party routers like "gorilla/mux." Here's an example using Gorilla Mux to define custom routes:

package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, Go with Gorilla Mux!")
})
router.HandleFunc("/products/{id:[0-9]+}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
fmt.Fprintf(w, "Product ID: %s", id)
})
http.Handle("/", router)
http.ListenAndServe(":8080", nil)
}

In this code, we use Gorilla Mux to create custom routes, including a route with a parameter for dynamic handling.


Further Resources

To continue learning about handling HTTP requests in Go, consider these resources: