← Back to list

Building a RESTful Microservice in Go

Go Rest Microservices

Jorge Gonzalez · 2024-10-20 15:06 · 43 claps · 2.2 min read
#go-language #restful-api #microservices #json
Open on Medium ↗

Building a RESTful Microservice in Go

Go Rest Microservices

Go Rest Microservices

Microservices have become the standard architecture for building scalable and maintainable applications. Go, with its simplicity and efficiency, is an excellent choice for developing such services. In this guide, we’ll go through the steps of creating a RESTful microservice in Go, complete with code snippets and explanations.

Table of Contents Introduction

  1. Setting Up Your Environment
  2. Creating Your Project Structure
  3. Writing the Main Application
  4. Defining Your Routes & Implementing Handlers
  5. Connecting to a Database
  6. Middlewares
  7. Testing Your Microservice
  8. Running and Deploying

1. Introduction

We’ll create a simple microservice that handles basic CRUD operations for a Book resource. Each book will have a title, author, and ISBN number.

2. Setting Up Your Environment

Ensure you have Go installed on your machine. You can download it from the official **Go website**.

Initialize your Go project:

mkdir go-microservice
cd go-microservice
go mod init go-microservice

3. Creating Your Project Structure

Organize your project with a clean structure:

go-microservice/
├── domain/
│   ├── model/
│   │   └── book.go
├── middleware/
│   └── logging.go
│   └── book_store.go
│   ├── routes/
│   │   └── book.go
└── go.mod
└── main.go

4. Writing the Main Application

In main.go, set up the main application and the HTTP server:

package main

import (
 handler "go-microservice/middleware/routes"
 "log"
 "net/http"
)

func main() {
 http.HandleFunc("/books", handler.BooksHandler)
 log.Fatal(http.ListenAndServe(":8080", nil))
}

5. Defining Your Routes & Implementing Handlers

In domain/routes/book.go, define your routes and handlers:

package routes

import (
 "encoding/json"
 "go-microservice/domain/model"
 "net/http"
)

func BooksHandler(w http.ResponseWriter, r *http.Request) {
 switch r.Method {
 case "GET":
  getBooks(w, r)
 case "POST":
  createBook(w, r)
 default:
  http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
 }
}

func getBooks(w http.ResponseWriter, r *http.Request) {
 books := []model.Book{
  {Title: "Book1", Author: "Author1", ISBN: "1234567890"},
 }
 jsonResponse(w, books, http.StatusOK)
}

func createBook(w http.ResponseWriter, r *http.Request) {
 var book model.Book
 err := json.NewDecoder(r.Body).Decode(&book)
 if err != nil {
  http.Error(w, err.Error(), http.StatusBadRequest)
  return
 }
 jsonResponse(w, map[string]string{"message": "Book created successfully"}, http.StatusCreated)
}

func jsonResponse(w http.ResponseWriter, data interface{}, statusCode int) {
 w.Header().Set("Content-Type", "application/json")
 w.WriteHeader(statusCode)
 json.NewEncoder(w).Encode(data)
}

Define the Book struct in domain/model/book.go:

package model

type Book struct {
    Title  string `json:"title"`
    Author string `json:"author"`
    ISBN   string `json:"isbn"`
}

6. Connecting to a Database

In middleware/book_store.go, set up the database connection:

package middleware

import (
 "database/sql"

 _ "github.com/lib/pq" // Postgres driver
)

func InitDB() *sql.DB {
 connStr := "user=username dbname=mydb sslmode=disable"
 db, err := sql.Open("postgres", connStr)
 if err != nil {
  panic(err)
 }
 return db
}

7. Middlewares

In middleware/logging.go, implement a logging middleware:

package middleware

import (
 "log"
 "net/http"
 "time"
)

func Logging(next http.Handler) http.Handler {
 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  start := time.Now()
  next.ServeHTTP(w, r)
  log.Printf("method=%s url=%s duration=%s\n", r.Method, r.URL, time.Since(start))
 })
}

8. Testing Your Microservice

Write tests to ensure your microservice works correctly. In book_test.go:

package routes

import (
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestGetBooks(t *testing.T) {
    req, err := http.NewRequest("GET", "/books", nil)
    if err != nil {
        t.Fatal(err)
    }

    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(getBooks)
    handler.ServeHTTP(rr, req)

    if status := rr.Code; status != http.StatusOK {
        t.Errorf("handler returned wrong status code: got %v want %v",
            status, http.StatusOK)
    }
}

9. Running and Deploying

Run your application:

go run main.go

For deployment, consider using Docker for containerization and Kubernetes for orchestration.


메타데이터
post_id
087e349fcff5
slug
building-a-restful-microservice-in-go-087e349fcff5
url
https://medium.com/@jorgegfx/building-a-restful-microservice-in-go-087e349fcff5
canonical_url
https://medium.com/@jorgegfx/building-a-restful-microservice-in-go-087e349fcff5
author_url
https://medium.com/@jorgegfx
status
ok
fetched_at
2026-06-27 07:40:21