国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Strategies for Integrating Golang Services with Existing Python Infrastructure Strategies for Integrating Golang Services with Existing Python Infrastructure Jul 02, 2025 pm 04:39 PM

TointegrateGolangserviceswithexistingPythoninfrastructure,useRESTAPIsorgRPCforinter-servicecommunication,allowingGoandPythonappstointeractseamlesslythroughstandardizedprotocols.1.UseRESTAPIs(viaframeworkslikeGininGoandFlaskinPython)orgRPC(withProtoco

Understanding the Performance Differences Between Golang and Python for Web APIs Understanding the Performance Differences Between Golang and Python for Web APIs Jul 03, 2025 am 02:40 AM

Golangofferssuperiorperformance,nativeconcurrencyviagoroutines,andefficientresourceusage,makingitidealforhigh-traffic,low-latencyAPIs;2.Python,whileslowerduetointerpretationandtheGIL,provideseasierdevelopment,arichecosystem,andisbettersuitedforI/O-bo

Is golang frontend or backend Is golang frontend or backend Jul 08, 2025 am 01:44 AM

Golang is mainly used for back-end development, but it can also play an indirect role in the front-end field. Its design goals focus on high-performance, concurrent processing and system-level programming, and are suitable for building back-end applications such as API servers, microservices, distributed systems, database operations and CLI tools. Although Golang is not the mainstream language for web front-end, it can be compiled into JavaScript through GopherJS, run on WebAssembly through TinyGo, or generate HTML pages with a template engine to participate in front-end development. However, modern front-end development still needs to rely on JavaScript/TypeScript and its ecosystem. Therefore, Golang is more suitable for the technology stack selection with high-performance backend as the core.

How to completely and cleanly uninstall Golang from my system? How to completely and cleanly uninstall Golang from my system? Jun 30, 2025 am 01:58 AM

TocompletelyuninstallGolang,firstdeterminehowitwasinstalled(packagemanager,binary,source,etc.),thenremoveGobinariesanddirectories,cleanupenvironmentvariables,anddeleterelatedtoolsandcaches.Beginbycheckinginstallationmethod:commonmethodsincludepackage

How to use channels for communication between goroutines in golang? How to use channels for communication between goroutines in golang? Jun 26, 2025 pm 12:08 PM

In Go language, channel is used for communication and synchronization between goroutines. Declare the use of make function, such as ch:=make(chanstring), send the ch

How to use the select statement in golang for non-blocking channel operations and timeouts? How to use the select statement in golang for non-blocking channel operations and timeouts? Jun 26, 2025 pm 01:08 PM

In Go, using select statements can effectively handle non-blocking channel operations and implement timeout mechanisms. Non-blocking reception or sending operations are realized through the default branch, such as 1. Non-blocking reception: if there is a value, it will be received and printed, otherwise the default branch will be executed immediately; 2. Non-blocking transmission: If there is no receiver in the channel, the sending will be skipped. In addition, timeout control can be implemented in conjunction with time.After, such as waiting for the result or returning after 2 seconds. You can also combine non-blocking and timeout behaviors, try to get the value immediately, and wait for a short time after failure, so as to improve the program's concurrent response capabilities.

What does the 'cannot find package' error mean during go build? What does the 'cannot find package' error mean during go build? Jun 26, 2025 pm 12:57 PM

When encountering a "cannotfindpackage" error, it is usually because Go cannot find the target package or dependency. The solution is as follows: 1. Check whether the import path is correct and ensure that it is consistent with the module path or directory structure; 2. Confirm that the go.mod file has been initialized and use gomodinit and gomodtidy to manage dependencies; 3. Run goget to download missing dependencies or clean the module cache; 4. Make sure to execute commands in the correct directory context, or specify the complete module relative path for construction.

How to marshal a golang struct to JSON with custom field names? How to marshal a golang struct to JSON with custom field names? Jun 30, 2025 am 01:59 AM

In Go, if you want the structure field to use a custom field name when converting to JSON, you can implement it through the json tag of the structure field. 1. Use the json: "custom_name" tag to specify the key name of the field in JSON. For example, Namestringjson: "username"" will make the Name field output as "username"; 2. Add, omitempty can control that the output is omitted when the field is empty, such as Emailstringjson: "email,omitempty""

See all articles