」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 Golang 使用 Api 閘道模式建立基本的微服務線上商店後端 - 第 1 部分

使用 Golang 使用 Api 閘道模式建立基本的微服務線上商店後端 - 第 1 部分

發佈於2024-11-08
瀏覽:378

Introduction

Hey, fellow developers! ? Ever thought about building a microservices architecture but felt overwhelmed by where to start? Worry no more! In this article, we'll build a basic microservices setup using the API Gateway pattern for an online store. And guess what? We'll do it all in Go (Golang)! ?

What You'll Learn

By the end of this guide, you’ll know how to:

  • Implement the API Gateway pattern in a microservices architecture.
  • Use gRPC for seamless communication between services.
  • Set up multiple microservices in Go with Docker.
  • Connect the dots and make everything work smoothly together!

Why Microservices? Why Go? Why API Gateway? ?

Before we dive into the code, let’s talk about why:

  • Microservices: Scalability, independent deployment, and flexibility.
  • Go: Fast, efficient, and ideal for building microservices.
  • **API **Gateway: Centralized entry point to handle all client requests and route them to the appropriate microservice.

Who said that? Me ?. Just kidding, but you'll soon be quoting this too when your app handles a gazillion users without breaking a sweat! Imagine your API dancing through the traffic while sipping coffee ☕. Yes, that’s the power of Microservices with Go and an API Gateway.

Oke, without further ado let's start it.

1. Setting Up Your Environment ?️

  • Install and download Go https://go.dev/doc/install
  • Use docker for your microservices https://docs.docker.com/engine/install/
  • Just use IDE that you want

2. Setup you project

/online-store
├── api-gateway/
├──── cmd/
├────── main.go
├──── internal/
├────── handler/
├──────── handler.go
├── services/
├──── user-service/
├────── cmd/
├──────── main.go
├────── internal/
├──────── handler/
├────────── handler.go
├────── proto/
├──────── user-proto
├────── Dockerfile
├──── /
├── docker-compose.yml
└── README.md

That's will be the dir structure the project, you can tweak it as you want, later we will also create pb directory do store generated pb file from our proto file.

Clone googleapis https://github.com/googleapis/googleapis, we will need that for our proto later. Just clone in root dir under online-store dir.

git clone https://github.com/googleapis/googleapis.git

3. Building the User Service ?

  • Initiate Go Mod
    Let's use our terminal and initiate our user-service go mod init
    go mod init user-service
    you can change "user-service" with your github url, but we will use it for now.

  • Create our first proto file for user
    create a new file under user-service/proto dir with name user.proto, let's use this proto code:

syntax = "proto3";

package order;

option go_package = ".";

import "google/api/annotations.proto";

service OrderService {
    rpc GetMyOrder(GetMyOrderRequest) returns (GetMyOrderResponse) {
        option (google.api.http) = {
            get: "/v1/order/my"
        };
    }
}

message GetMyOrderRequest {
    string user_id = 1;
}

message GetMyOrderResponse {
    string  user_id = 1;
    string order_id = 2;
    string product_id = 3;
    int32 quantity = 4;
    float price = 5;
    string status = 6;
}
  • Use protoc to generate gRPC First, we need to create pb dir under service/user-service to store our generated grpc files and run this command to generate our gRPC:
protoc --proto_path="services/user-service/proto" \
        --go_out="services/user-service/pb" \
        --go-grpc_out="services/user-service/pb" \
        --grpc-gateway_out="services/user-service/pb" \
        "services/user-service/proto/user.proto"

With that command we will generate 3 files (user_grpc.pb.go, user_pb.go, and user.pb.gw.go) and will place them into services/user-service/pb directory.

But, because we want use the same grpc to our Api Gateway, we need to copy them too into api-gateway/pb directory. You can copy it manually each time you generate grpc, but let's just use script for it.

I create a new dir online-store/scripts to store all scripts. Let's create a new file generate-proto.sh, and put this code:

#!/bin/bash

# Error handling function
handle_error() {
  echo "Error occurred in script at line: $1"
  exit 1
}

# Trap any error and call the handle_error function
trap 'handle_error $LINENO' ERR

# Declare an associative array to map proto directories to their corresponding pb directories
declare -A dir_map=(
  ["services/user-service/proto"]="services/user-service/pb"
  # you can add another directory here
  # e.g ["services/order-service/proto"]="services/order-service/pb"
)

# Define Static Dir Path
GOOGLEAPIS_DIR="googleapis"
API_GATEWAY_PB_DIR="api-gateway/pb"

# Ensure the API_GATEWAY_PB_DIR exists
if [ ! -d "$API_GATEWAY_PB_DIR" ]; then
  mkdir -p "$API_GATEWAY_PB_DIR"
  echo "Directory $API_GATEWAY_PB_DIR created."
else 
  echo "Directory $API_GATEWAY_PB_DIR already exists."
fi

# Loop through the associative array and generate Go code for each proto directory
for proto_dir in "${!dir_map[@]}"; do
  pb_dir="${dir_map[$proto_dir]}"

  # Check if the pb directory exists, if not, create it
  if [ ! -d "$pb_dir" ]; then
    mkdir -p "$pb_dir"
    echo "Directory $pb_dir created."
  else
    echo "Directory $pb_dir already exists."
  fi

  # Process each .proto file in the proto directory
  for proto_file in "$proto_dir"/*.proto; do
    # Ensure the proto file exists
    if [ -f "$proto_file" ]; then
      # Generate Go code for the current proto file
      protoc --proto_path="$proto_dir" \
        --proto_path="$GOOGLEAPIS_DIR" \
        --go_out="$pb_dir" \
        --go-grpc_out="$pb_dir" \
        --grpc-gateway_out="$pb_dir" \
        "$proto_file"
      echo "Generated Go code for $proto_file"

      # Copy the generated Go code to the API Gateway directory
      cp -auv "$pb_dir"/* "$API_GATEWAY_PB_DIR/"
      echo "Copied generated Go code to $API_GATEWAY_PB_DIR from $pb_dir"
    else
      echo "No .proto files found in $proto_dir."
    fi
  done
done

That script will create you a new pb directory if it's does not exist.

Now, lets execute our script:

./scripts/generate-proto.sh

You will need to install some packages:

go get github.com/grpc-ecosystem/grpc-gateway/v2
go get google.golang.org/genproto/googleapis/api
go get .golang.org/protobuf

If you get some error regarding import, do this comman go mod tidy

  • Create our user handler code create a user-handler.go file under services/user-services/internal/handler directory, use let's use this simple code:
package handler

import (
    "context"
    "log"

    pb "user-service/pb"

    "google.golang.org/grpc"
)

// server implements the UserServiceServer interface
type server struct {
    pb.UnimplementedUserServiceServer
}

// NewServer creates a new instance of server
func NewServer() pb.UserServiceServer {
    return &server{}
}

// Implement the methods defined in your proto file here
func (s *server) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.GetUserResponse, error) {
    // Log the request details
    log.Printf("Received GetUser request with ID: %s", req.GetId())

    // Implement your logic to get user information
    response := &pb.GetUserResponse{
        Id:    req.GetId(),
        Name:  "John Doe",
        Email: "[email protected]",
    }

    // Log the response details
    log.Printf("Returning GetUser response: % v", response)

    return response, nil
}

// Implement GetUserProfile method
func (s *server) GetUserProfile(ctx context.Context, req *pb.GetUserProfileRequest) (*pb.GetUserProfileResponse, error) {
    // Log the request details
    log.Printf("Received GetUserProfile request with ID: %s", req.GetId())

    response := &pb.GetUserProfileResponse{
        Id:      req.GetId(),
        Name:    "John Doe",
        Email:   "[email protected]",
        Phone:   "1234567890",
        Address: "123 Main St",
    }

    // Log the response details
    log.Printf("Returning GetUserProfile response: % v", response)

    return response, nil
}

// RegisterServices registers the gRPC services with the server
func RegisterServices(s *grpc.Server) {
    pb.RegisterUserServiceServer(s, NewServer())
}

You will need to install some package:

go get google.golang.org/grpc
  • Create our main.go file in user-service/cmd/main.go We use this simple code for our main code:
package main

import (
    "log"
    "net"

    "google.golang.org/grpc"
    "google.golang.org/grpc/reflection"

    "user-service/internal/handler"
)

func main() {
    // Create a new gRPC server
    s := grpc.NewServer()

    // Register the server with the gRPC server
    handler.RegisterServices(s)

    // Register reflection service on gRPC server
    reflection.Register(s)

    // Listen on port 50051
    lis, err := net.Listen("tcp", ":50051")
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }

    // Start the gRPC server
    log.Println("Starting gRPC server on :50051")
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

You need to install google.golang.org/grpc/reflection, with this package we can look into our services.

  • Create Dockerfile for user-service create a new file in user-service directory with name Dockerfile, use this for our Dockerfile:
# Stage 1: Build
FROM golang:1.23 AS builder

WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./
RUN go mod download

# Copy the application code
COPY . .

# Build the Go application
RUN go build -o user-service ./cmd

# Stage 2: Run
FROM ubuntu:22.04

# Install necessary libraries
RUN apt-get update && apt-get install -y \
    ca-certificates \
    libc6 \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy the binary from the build stage
COPY --from=builder /app/user-service /app/user-service

ENTRYPOINT ["/app/user-service"]

# Expose port
EXPOSE 50051

4. Build Api Gateway

Because we already have pb files generated under api-gateway/pb directory. Now, we can create handler for our api-gateway, create a new file api-gateway/internal/handler/service-regitry.go, use this code to register our services:

package handler

import (
    "context"
    "log"

    "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
    "google.golang.org/grpc"

    pb "api-gateway/pb"
)

// ServiceConfig holds the configuration for each service.
type ServiceConfig struct {
    Name    string
    Address string
}

// RegisterServices registers all services with the mux based on the given service configurations.
func RegisterServices(ctx context.Context, mux *runtime.ServeMux, services []ServiceConfig) error {
    for _, svc := range services {
        opts := []grpc.DialOption{grpc.WithInsecure()}
        var err error
        switch svc.Name {
        case "UserService":
            err = pb.RegisterUserServiceHandlerFromEndpoint(ctx, mux, svc.Address, opts)
        // We can create another cases for another services
        default:
            log.Printf("No handler implemented for service %s", svc.Name)
            continue
        }
        if err != nil {
            return err
        }
        log.Printf("Registered service %s at %s", svc.Name, svc.Address)
    }
    return nil
}

You will also need to install these in api-gateway:

go get github.com/grpc-ecosystem/grpc-gateway
go get google.golang.org/grpc
  • Create our main.go in Api Gateway Now, create a new file api-gateway/cmd/main.go for our main code, use this code:
package main

import (
    "context"
    "log"
    "net/http"

    "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"

    "api-gateway/internal/handler"
)

func main() {
    // Define service configurations
    services := []handler.ServiceConfig{
        {Name: "UserService", Address: "user-service:50051"},
        // You can add another services here
    }

    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()

    mux := runtime.NewServeMux()

    // Register services
    if err := handler.RegisterServices(ctx, mux, services); err != nil {
        log.Fatalf("Failed to register services: %v", err)
    }

    // Start the HTTP server
    if err := http.ListenAndServe(":8080", mux); err != nil {
        log.Fatalf("Failed to start HTTP server: %v", err)
    }
}

  • Create Dockerfile for Api Gateway We also need Dockerfile for Api Gateway, create a new file api-gateway/Dockerfile and use this config:
# Stage 1: Build
FROM golang:1.23 AS builder

WORKDIR /app

# Copy go mod and sum files
COPY go.mod go.sum ./
RUN go mod download

# Copy the application code
COPY . .

# Build the Go application
RUN go build -o main ./cmd

# Stage 2: Run
FROM ubuntu:22.04

# Install necessary libraries
RUN apt-get update && apt-get install -y \
    ca-certificates \
    libc6 \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy the binary from the build stage
COPY --from=builder /app/main /app/main

ENTRYPOINT ["/app/main"]

# Expose port (if necessary)
EXPOSE 8080
  • Create docker-compose.yml Oke, we also need to create a online-store/docker-compose.yml file, use use copy:
version: '4.0'
services:
  api-gateway:
    build: ./api-gateway
    ports:
      - "8080:8080"
    depends_on:
      - user-service

  user-service:
    build: 
      context: ./services/user-service
      dockerfile: Dockerfile
    ports:
      - "50051:50051"

  # Can put another service here

5. Start our Microservice

Because we use docker, make sure your docker already active.
And we can run with this command:

docker-compose up --build -d

You will see your services already up. (I use windows)

Build basic microservice online store backend with Golang use Api Gateway Pattern - Part 1

You can also use this command to see active service:

docker ps

Build basic microservice online store backend with Golang use Api Gateway Pattern - Part 1

You see that i also have another services, you can also add it to your code.

6. Hit our endpoint

I use postman to hit user-service endpoint

Build basic microservice online store backend with Golang use Api Gateway Pattern - Part 1

Because we also put log code in our user-service, we can do this command to look into our service logs:

docker logs --follow user-service-1

Make sure service name by looks into our active service docker ps

Then you will see this log:

Build basic microservice online store backend with Golang use Api Gateway Pattern - Part 1

Conclusion ?

Congratulations! ? You've just built a basic microservices architecture for an online store using Go, gRPC, Docker. Keep experimenting and improving your setup. We will continue to build our online-store until finish, stay tune ?‍??

Repository: https://github.com/agustrinaldokurniawan/online-store/tree/main/backend

版本聲明 本文轉載於:https://dev.to/agustrinaldokurniawan/build-basic-microservice-online-store-backend-with-golang-use-api-gateway-pattern-1bf?1如有侵犯,請聯絡study_golang@163 .com刪除
最新教學 更多>
  • PDO如何防止SQL注入並取代轉義單引號?
    PDO如何防止SQL注入並取代轉義單引號?
    PDO防止SQL注入的方法如果你已經從mysql函式庫過渡到PDO,你可能想知道如何取代real_escape_string來轉義發往資料庫的字串中的單引號的函數。雖然向每個字串添加斜杠可能看起來很麻煩,但 PDO 提供了一種更有效的替代方案。 PDO 準備的強大功能為了防止 SQL 注入,PDO ...
    程式設計 發佈於2024-11-09
  • 透過「專案:使用互斥體同步多執行緒列印」課程釋放您的編碼潛力
    透過「專案:使用互斥體同步多執行緒列印」課程釋放您的編碼潛力
    您準備好深入多執行緒程式設計的世界並學習如何使用互斥體來同步字串的列印了嗎? LabEx 提供的項目:使用互斥體同步多執行緒列印課程就是您的最佳選擇。 在這個基於專案的綜合課程中,您將踏上了解互斥體在協調多執行緒執行方面的重要性的旅程。您將首先修改現有的「混沌打字機」程序,確保字串以正確的順序列印...
    程式設計 發佈於2024-11-09
  • 為什麼我在 MySQL 中收到「\'create_date\'時間戳欄位的預設值無效」錯誤?
    為什麼我在 MySQL 中收到「\'create_date\'時間戳欄位的預設值無效」錯誤?
    “create_date”時間戳字段的預設值無效建立帶有時間戳列的表並指定預設值“0000-”時00-00 00:00:00',可能會出現錯誤,指示「'create_date'的預設值無效」。這個錯誤是由 MySQL 的 SQL 模式 - NO_ZERO_DATE 所造成的。...
    程式設計 發佈於2024-11-09
  • 儘管出現「頁面已移動」錯誤,如何使用 cURL 檢索頁面內容?
    儘管出現「頁面已移動」錯誤,如何使用 cURL 檢索頁面內容?
    使用 cURL 檢索頁面內容在此上下文中,您試圖使用 cURL 抓取 Google 搜尋結果頁面的內容。儘管嘗試設定使用者代理程式和各種選項,但您仍無法成功檢索頁面內容。重定向或“頁面移動”錯誤繼續困擾著您。 據信此問題可能源自於查詢字串中特殊字元的編碼。為了緩解這種情況,需要更改 PHP 程式碼。...
    程式設計 發佈於2024-11-09
  • 如何使用 JPA 和 Hibernate 以 UTC 格式儲存日期/時間?
    如何使用 JPA 和 Hibernate 以 UTC 格式儲存日期/時間?
    使用JPA 和Hibernate 在UTC 時區儲存日期/時間在JPA/ 中處理日期和時間時擔心時區差異休眠應用程式?本文探討如何在 UTC (GMT) 時區有效儲存和檢索時態數據,確保跨不同時區進行一致且準確的處理。 考慮以下附註的 JPA 實體:public class Event { ...
    程式設計 發佈於2024-11-09
  • 如何使用 CSS 建立動態擴充的文字輸入欄位?
    如何使用 CSS 建立動態擴充的文字輸入欄位?
    透過 CSS 增強文字輸入回應能力製作 Web 表單時,控製文字輸入欄位的大小至關重要。 CSS 提供了一種簡單的方法來定義其初始尺寸。但是,如果您希望輸入隨著使用者鍵入而動態擴展並達到最大寬度,該怎麼辦?本文深入研究了僅 CSS 和基於 HTML 的技術來實現此行為。 CSS 和內容可編輯利用 C...
    程式設計 發佈於2024-11-09
  • 關於 Javascript Promise 的有趣事實
    關於 Javascript Promise 的有趣事實
    Promise 始終是異步的 Promise 的回呼總是在同步程式碼之後執行 const promise = Promise.resolve(); promise.then(() => console.log('async')); console.log('sync');...
    程式設計 發佈於2024-11-09
  • LightFlow:Go 的任務編排框架
    LightFlow:Go 的任務編排框架
    我發展了 LightFlow,一個任務編排框架,旨在簡化 Go 中複雜工作流程的管理。它專注於執行時序並減少對外部設定檔的需求。 主要特點: 獨立上下文:每個步驟都通過獨立上下文鏈接,僅允許訪問相關數據。 可合併流程:您可以靈活組合任務流程,以便在不同流程中重複使用。 檢查點恢...
    程式設計 發佈於2024-11-09
  • 使用 HTML、CSS 和 JavaScript 建立簡單的連結檢查器工具
    使用 HTML、CSS 和 JavaScript 建立簡單的連結檢查器工具
    使用 HTML、CSS 和 JavaScript 建立簡單的連結檢查器工具 作為...
    程式設計 發佈於2024-11-09
  • ## 為什麼 GetSystemTimeAdjustment 並不總是反映 Windows 7 上的真實時間調整?
    ## 為什麼 GetSystemTimeAdjustment 並不總是反映 Windows 7 上的真實時間調整?
    Windows 7 計時函數:了解GetSystemTimeAdjustment如您所觀察到的,在Windows 7 上使用GetSystemTimeAdjustment 函數的結果可能會令人費解。為了更好地理解,讓我們解決您的問題:問題1:假設的正確性您的假設總體上是正確的。如果系統時間定期同步,...
    程式設計 發佈於2024-11-09
  • 掌握 JavaScript:初學者的基本技巧
    掌握 JavaScript:初學者的基本技巧
    JavaScript 是一種多功能且功能強大的程式語言,構成了現代 Web 開發的支柱。如果您是 JavaScript 新手,這裡有一些基本技巧可幫助您掌握其概念並開始建立互動式 Web 應用程式: 1. 了解基礎: 變數和資料類型:了解變數、它們的類型(數字、字串、布林值、物件、陣...
    程式設計 發佈於2024-11-09
  • 如何在 Python 中安全地儲存使用者憑證而不損害資料隱私?
    如何在 Python 中安全地儲存使用者憑證而不損害資料隱私?
    在 Python 中保護使用者憑證在 Python 中,儲存使用者名稱和密碼等敏感資訊需要仔細考慮。在編寫定期從第三方服務檢索資料等任務的腳本時,您需要一種可靠且安全的方法來儲存憑證而不損害資料隱私。 一個選擇是利用 Python 金鑰環庫,它與作業系統加密整合機制。在 Windows 中,金鑰環採...
    程式設計 發佈於2024-11-09
  • 在 Go 中何時使用限制為切片類型的切片參數與通用切片參數?
    在 Go 中何時使用限制為切片類型的切片參數與通用切片參數?
    泛型切片參數:理解區別在Go 中,泛型編程引入了類型參數,允許函數對不同類型進行操作。感興趣的一個領域是限制為切片類型的切片參數和通用切片參數之間的區別。 限制為切片類型的切片參數考慮使用 slices.Grow 函數第一個參數受 ~[]E 約束。這意味著該參數的類型必須是元素類型為 E 的切片類型...
    程式設計 發佈於2024-11-09
  • 簡單DIY心率監測器+心電圖顯示器
    簡單DIY心率監測器+心電圖顯示器
    目標 這個迷你專案/教學的目標是用最少的組件製作一個超級簡單的心率監視器和滾動心電圖顯示。 要求: Python 音訊介面 1/4吋線/吉他線/樂器線(只需透過音訊介面連接電腦即可) 快速背景 心臟的肌肉產生電訊號。其中一些訊號可以在皮膚表面檢測到。 我們可以使用表面電極來擷取這些訊號。問題是,...
    程式設計 發佈於2024-11-09
  • 生態倡議地圖:CSS(第 2 部分)
    生態倡議地圖:CSS(第 2 部分)
    Introducción En este tutorial, aprenderás cómo mejorar la apariencia visual de tu página HTML aplicando estilos CSS de manera gradual. A lo l...
    程式設計 發佈於2024-11-09

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3