Home  >  Article  >  Backend Development  >  Building a simple REST API with Go

Building a simple REST API with Go

Susan Sarandon
Susan SarandonOriginal
2024-10-31 22:06:44540browse

Building a simple REST API with Go

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

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"
)

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`
}

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"},
}

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))
}

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)
}

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)
}

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)
}

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)
}

Using the API

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

go run main.go

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

List all servers:

curl localhost:8080/servers

Get a specific server:

curl localhost:8080/servers/srv1

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"}';

Delete a server:

curl -X DELETE localhost:8080/servers/srv1

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.

The above is the detailed content of Building a simple REST API with Go. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn