DEV Community

Pasindu Dewviman
Pasindu Dewviman

Posted on

Building a REST API in Go (Golang)

Go, also known as Golang, is renowned for its simplicity, performance, and built-in concurrency support, making it an excellent choice for building RESTful APIs. Companies like Docker, Kubernetes, and Uber rely on Go for high-performance backend services. In 2025, Go continues to dominate API development due to its efficiency and robust ecosystem.

What is a REST API?

REST (Representational State Transfer) is an architectural style for designing networked applications. It uses standard HTTP methods to perform CRUD operations on resources:

GET: Retrieve a resource
POST: Create a resource
PUT/PATCH: Update a resource
DELETE: Delete a resource

Resources are identified by URLs (e.g., /users/123), and responses are typically in JSON format.

Why Choose Go for REST APIs?

  • Performance: Compiled to machine code with low latency and high throughput.
  • Concurrency: Goroutines handle thousands of requests efficiently.
  • Standard Library: net/http provides everything needed for basic servers.

Options for Building REST APIs in Go

  1. Standard Library (net/http) Ideal for learning or lightweight APIs. Go 1.22+ improved ServeMux with method-specific routing (e.g., HandleFunc("GET /users", handler)). Example basic server:
package main

import (
    "encoding/json"
    "net/http"
)

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

var users = []User{{ID: 1, Name: "Alice"}}

func getUsers(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodGet {
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        return
    }
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(users)
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /users", getUsers)
    http.ListenAndServe(":8080", mux)
}
Enter fullscreen mode Exit fullscreen mode

Building a Simple REST API with Gin

Let's create a basic user management API.

Setup:Bashgo mod init rest-api-example
go get github.com/gin-gonic/gin

Code (main.go):

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

var users = []User{{ID: 1, Name: "Alice"}}

func main() {
    r := gin.Default()

    r.GET("/users", getUsers)
    r.GET("/users/:id", getUser)
    r.POST("/users", createUser)

    r.Run(":8080")
}

func getUsers(c *gin.Context) {
    c.JSON(http.StatusOK, users)
}

func getUser(c *gin.Context) {
    id := c.Param("id")
    // Parse and find user...
    c.JSON(http.StatusOK, gin.H{"id": id})
}

func createUser(c *gin.Context) {
    var newUser User
    if err := c.BindJSON(&newUser); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    users = append(users, newUser)
    c.JSON(http.StatusCreated, newUser)
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)