Back to Course
Web Development

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 POST requests to add new resources.
  • Read — handle GET requests to fetch resources.
  • Update — handle PUT/PATCH requests to modify resources.
  • Delete — handle DELETE requests 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.

Ready to master real-world Go skills?

Learn Go hands-on with mentor-led, live sessions.

Explore Course