prakash chokalingam
Posted on February 15, 2024
Transitioning from Node.js or Python development, you're likely familiar with the convenience of frameworks like Express or Flask for spinning up HTTP servers with rich routing capabilities. Similarly, in the Go ecosystem, frameworks such as Gin and Gorilla/Mux have been the go-to solutions for developers seeking to implement efficient routing within their applications.
However, the landscape has evolved with the release of Go 1.22. The net/http package, a staple for network-related operations in Go, has received significant enhancements, particularly in its routing capabilities. This evolution means that developers can now implement complex HTTP servers without relying on external frameworks, streamlining the development process and reducing dependency overhead.
Here's how to build a simple todo application using the net/http server mux.
package main
import (
"fmt"
"net/http"
)
func main() {
router := http.NewServeMux()
router.HandleFunc("POST /todos", func(w http.ResponseWriter, r *http.Request) {
fmt.Println("create a todo")
})
router.HandleFunc("GET /todos", func(w http.ResponseWriter, r *http.Request) {
fmt.Println("get all todos")
})
router.HandleFunc("PATCH /todos/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
fmt.Println("update a todo by id", id)
})
router.HandleFunc("DELETE /todos/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
fmt.Println("delete a todo by id", id)
})
http.ListenAndServe(":8080", router)
}
You can also create a route that matches exactly or uses a wildcard for flexible matching.
// wild card
router.HandleFunc("PATCH /todos/{rest...}", func(w http.ResponseWriter, r *http.Request) {
rest := r.PathValue("rest")
fmt.Println("wild card route", rest)
})
// exact match
router.HandleFunc("/todos/{$}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "exact match")
})
For more details deep dive into the official go documentation https://pkg.go.dev/net/http#ServeMux.
Posted on February 15, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.