Home Backend Development Golang Building a simple REST API with Go

Building a simple REST API with Go

Oct 31, 2024 pm 10:06 PM

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
Copy after login

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"
)
Copy after login

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`
}
Copy after login

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"},
}
Copy after login

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))
}
Copy after login

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)
}
Copy after login

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)
}
Copy after login

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)
}
Copy after login

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)
}
Copy after login

Using the API

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

go run main.go
Copy after login

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

List all servers:

curl localhost:8080/servers
Copy after login

Get a specific server:

curl localhost:8080/servers/srv1
Copy after login

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

Delete a server:

curl -X DELETE localhost:8080/servers/srv1
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

See all articles