How to Build a REST API in Go using net/http – Complete CRUD
Setting Up a Basic HTTP Server
package main
import (
"encoding/json"
"net/http"
)
func getUsers(w http.ResponseWriter, r *http.Request) {
users := []string{"Alice", "Bob"}
json.NewEncoder(w).Encode(users)
}
func main() {
http.HandleFunc("/users", getUsers)
http.ListenAndServe(":8080", nil)
}
Handling Different HTTP Methods
func userHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
// fetch and return users
case "POST":
// create a new user
case "PUT":
// update an existing user
case "DELETE":
// remove a user
}
}
CRUD Overview
- Create — handle
POSTrequests to add new resources. - Read — handle
GETrequests to fetch resources. - Update — handle
PUT/PATCHrequests to modify resources. - Delete — handle
DELETErequests to remove resources.
For larger APIs, frameworks like Gin or Chi simplify routing, but net/http alone is enough to build a fully functional REST API.
PreviousChannels in Go – Buffered, Unbuffered, and Select Statement
Next Go Modules Tutorial – Managing Dependencies like a Pro
Ready to master real-world Go skills?
Learn Go hands-on with mentor-led, live sessions.
.png)