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!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1378
52
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.
How do you use the pprof tool to analyze Go performance?
Mar 21, 2025 pm 06:37 PM
The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159
How do you write unit tests in Go?
Mar 21, 2025 pm 06:34 PM
The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.
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 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...
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,...
What is the go fmt command and why is it important?
Mar 20, 2025 pm 04:21 PM
The article discusses the go fmt command in Go programming, which formats code to adhere to official style guidelines. It highlights the importance of go fmt for maintaining code consistency, readability, and reducing style debates. Best practices fo
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...


