Building a simple REST API with Go

Sam Newby - Oct 27 - - Dev Community

Go is a great language for systems programming but it also shines on the web, especially when building REST APIs. This guide walks through creating a simple REST API using Go's standard library. We'll build an API to manage a list of servers, letting us add, remove, and view server records. We're also going to use Go 1.22 new router enhancements for method matching which allows us to have cleaner routes and handlers.

This guide assumes you have a basic understanding of Go and it installed on your machine.

Setting Up

Create a new directory for your project and initialize a Go module:

mkdir server-api
cd server-api
go mod init server-api
Enter fullscreen mode Exit fullscreen mode

The Code

Create a file called main.go. We'll use Go's standard http package - it has everything we need for a basic API.

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)
Enter fullscreen mode Exit fullscreen mode

First, let's define what a server looks like. We'll keep it simple - just an ID, name, IP address, and region:

type Server struct {
    ID     string `json:"id"`
    Name   string `json:"name"`
    IP     string `json:"ip"`
    Region string `json:"region`
}
Enter fullscreen mode Exit fullscreen mode

We'll store our servers in memory using a slice. In a real application, you'd probably use a database:

var servers = []Server{
    {ID: "srv1", Name: "prod-1", IP: "10.0.1.1", Region: "us-east"},
    {ID: "srv2", Name: "prod-2", IP: "10.0.1.2", Region: "eu-west"},
}
Enter fullscreen mode Exit fullscreen mode

Creating the router

Next, we'll set up our routes. Go 1.22 introduced a new routing syntax that makes this pretty straightforward:

func main() {
    mux := http.NewServeMux()

    mux.HandleFunc("GET /servers", listServers)
    mux.HandleFunc("GET /servers/{id}", showServer)
    mux.HandleFunc("POST /servers", createServer)
    mux.HandleFunc("DELETE /servers/{id}", deleteServer)

    fmt.Println("Server starting on port 8080...")
    log.Fatal(http.ListenAndServe(":8080", mux))
}
Enter fullscreen mode Exit fullscreen mode

Handlers

Now let's implement each handler. First, listing all servers:

func listServers(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(servers)
}
Enter fullscreen mode Exit fullscreen mode

Getting a single server by ID:

func showServer(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    id := r.PathValue("id")

    for _, server := range servers {
        if server.ID == id {
            json.NewEncoder(w).Encode(server)
            return
        }
    }

    http.Error(w, "Server not found", http.StatusNotFound)
}
Enter fullscreen mode Exit fullscreen mode

Creating a new server:

func createServer(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")

    var server Server
    if err := json.NewDecoder(r.Body).Decode(&server); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    servers = append(servers, server)
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(server)
}
Enter fullscreen mode Exit fullscreen mode

And finally, deleting a server:

func deleteServer(w http.ResponseWriter, r *http.Request) {
    id := r.PathValue("id")

    for i, server := range servers {
        if server.ID == id {
            servers = append(servers[:i], servers[i+1:]...)
            w.WriteHeader(http.StatusNoContent)
            return
        }
    }

    http.Error(w, "Server not found", http.StatusNotFound)
}
Enter fullscreen mode Exit fullscreen mode

Using the API

Once you've got the code in place, run it:

go run main.go
Enter fullscreen mode Exit fullscreen mode

Here's how to interact with each endpoint using cURL:

List all servers:

curl localhost:8080/servers
Enter fullscreen mode Exit fullscreen mode

Get a specific server:

curl localhost:8080/servers/srv1
Enter fullscreen mode Exit fullscreen mode

Add a server:

curl -X POST localhost:8080/servers   -H "Content-Type: application/json";   -d '{"id":"srv3","name":"prod-3","ip":"10.0.1.3","region":"ap-south"}';
Enter fullscreen mode Exit fullscreen mode

Delete a server:

curl -X DELETE localhost:8080/servers/srv1
Enter fullscreen mode Exit fullscreen mode

What's Next?

This is a basic API, but there's a lot you could add:

  • Input validation
  • Proper error handling
  • Persisting servers with a database such as PostgreSQL
  • Authentication
  • Request logging
  • Unit tests

The standard library is surprisingly capable for building APIs. While there are more full-featured frameworks available, starting with the standard library helps you understand the basics without any magic happening behind the scenes.

. . .