首页  >  文章  >  后端开发  >  使用 Go、PostgreSQL、Google Cloud 和 CockroachDB 构建 API

使用 Go、PostgreSQL、Google Cloud 和 CockroachDB 构建 API

Linda Hamilton
Linda Hamilton原创
2024-10-24 07:02:30758浏览

我使用 Go 和 PostgreSQL 构建了一个 API,使用 Google Cloud Run、Cloud Build、Secret Manager 和 ArtifactRegistry 设置了 CI/CD 管道,并将 Cloud Run 实例连接到 CockroachDB。

该API基于游戏《核心危机:最终幻想VII》,模拟“物质融合”。本文的目标受众是只想了解如何构建和部署 API 的开发人员。我还有另一篇文章,其中讨论了我在从事该项目时学到的所有内容、哪些内容不起作用,以及理解和翻译游戏的材质融合规则(链接即将推出)。

方便参考的链接

  • GitHub 存储库和自述文件
  • Swagger (OpenAPI) 文档和测试
  • 公共邮递员收藏
  • 领域模型来源

API目标

3 个端点 - 健康检查 (GET)、所有材料列表 (GET) 和模拟材料融合 (POST)

领域模型

物质(单数和复数)是一个水晶球,作为魔法的来源。游戏中有 144 种不同的材质,大致分为 4 类:“魔法”、“命令”、“支持”和“独立”。然而,为了弄清楚物质融合的规则,根据它们的融合行为,更容易有32个内部类别,以及这些类别内的8个等级(参见参考资料) .

一种材料在使用一定时间后就会变得“精通”。持续时间在这里并不重要。

最重要的是,两种材质可以融合产生一种新材质。融合规则受以下因素影响:

  • 是否掌握其中一种或两种材料。
  • 哪一种材料先出现(如 X Y 不一定等于 Y X)。
  • 材质内部类别。
  • 材质等级。

Building an API with Go, PostgreSQL, Google Cloud and CockroachDB

并且有很多例外,其中一些规则具有 3 层嵌套的 if-else 逻辑。这消除了在数据库中创建一个简单表并将 1000 条规则保存到其中的可能性,或者想出一个公式来规则所有规则的可能性。

简而言之,我们需要:

  1. 一个表材质,其中包含列 name(string)、materia_type(ENUM)(32 个内部类别)、grade(integer)、display_materia_type(ENUM)(游戏中使用的 4 个类别)、description(string) 和 id(整数)作为自增主键。
  2. 封装基本规则格式MateriaTypeA MateriaTypeB = MateriaTypeC的数据结构。
  3. 使用基本和复杂规则来确定输出材料的内部类别和等级的代码。

1. 设置本地 PostgreSQL 数据库

理想情况下,您可以从网站本身安装数据库。但是pgAdmin工具由于某种原因无法连接到DB,所以我使用了Homebrew。

安装

brew install postgresql@17

这将安装一大堆 CLI 二进制文件以帮助使用数据库。

可选:将 /opt/homebrew/opt/postgresql@17/bin 添加到 $PATH 变量。

# create the DB
createdb materiafusiondb
# step into the DB to perform SQL commands
psql materiafusiondb

创建用户和权限

-- create an SQL user to be used by the Go server
CREATE USER go_client WITH PASSWORD 'xxxxxxxx';

-- The Go server doesn't ever need to add data to the DB. 
-- So let's give it just read permission.
CREATE ROLE readonly_role;
GRANT USAGE ON SCHEMA public TO readonly_role;

-- This command gives SELECT access to all future created tables. 
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly_role;

-- If you want to be more strict and give access only to tables that already exist, use this:
-- GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_role;

GRANT readonly_role TO go_client;

创建表

CREATE TYPE display_materia_type AS ENUM ('Magic', 'Command', 'Support', 'Independent');

CREATE TYPE materia_type AS ENUM ('Fire', 'Ice', 'Lightning', 'Restore', 'Full Cure', 'Status Defense', 'Defense', 'Absorb Magic', 'Status Magic', 'Fire & Status', 'Ice & Status', 'Lightning & Status', 'Gravity', 'Ultimate', 'Quick Attack', 'Quick Attack & Status', 'Blade Arts', 'Blade Arts & Status', 'Fire Blade', 'Ice Blade', 'Lightning Blade', 'Absorb Blade', 'Item', 'Punch', 'SP Turbo', 'HP Up', 'AP Up', 'ATK Up', 'VIT Up', 'MAG Up', 'SPR Up', 'Dash', 'Dualcast', 'DMW', 'Libra', 'MP Up', 'Anything');

CREATE TABLE materia (
    id integer NOT NULL,
    name character varying(50) NOT NULL,
    materia_type materia_type NOT NULL,
    grade integer NOT NULL,
    display_materia_type display_materia_type,
    description text
    CONSTRAINT materia_pkey PRIMARY KEY (id)
);

-- The primary key 'id' should auto-increment by 1 for every row entry.
CREATE SEQUENCE materia_id_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

ALTER SEQUENCE materia_id_seq OWNED BY materia.id;

ALTER TABLE ONLY materia ALTER COLUMN id SET DEFAULT nextval('materia_id_seq'::REGCLASS);

添加数据

创建包含表头和数据的 Excel 工作表,并将其导出为 CSV 文件。然后运行命令:

COPY materia(name,materia_type,grade,display_materia_type,description) FROM
 '<path_to_csv_file>/materiadata.csv' DELIMITER ',' CSV HEADER;

2. 创建Go服务器

使用 autostrada.dev 创建样板代码。添加 api、postgresql、httprouter、env var config、tintedlogging、git、live reload、makefile 的选项。我们最终得到这样的文件结构:

? codebase
├─ cmd
│  └─ api
│     ├─ errors.go
│     ├─ handlers.go
│     ├─ helpers.go
│     ├─ main.go
│     ├─ middleware.go
│     └─ server.go
├─ internal
│  ├─ database --- db.go
│  ├─ env --- env.go
│  ├─ request --- json.go
│  ├─ response --- json.go
│  └─ validator
│     ├─ helpers.go
│     └─ validators.go
├─ go.mod
├─ LICENSE
├─ Makefile
├─ README.md
└─ README.html

.env 文件

样板生成器已创建代码来获取环境变量并将它们添加到代码中,但我们可以更轻松地跟踪和更新值。

创建 /.env 文件。添加以下值:

HTTP_PORT=4444
DB_DSN=go_client:<password>@localhost:5432/materiafusiondb?sslmode=disable
API_TIMEOUT_SECONDS=5
API_CALLS_ALLOWED_PER_SECOND=1

添加 godotenv 库:

go get github.com/joho/godotenv

将以下内容添加到 main.go:

// At the beginning of main():
err := godotenv.Load(".env") // Loads environment variables from .env file
if err != nil { // This will be true in prod, but that's fine.
  fmt.Println("Error loading .env file")
}


// Modify config struct:
type config struct {
  baseURL string
  db      struct {
    dsn string
  }
  httpPort                 int
  apiTimeout               int
  apiCallsAllowedPerSecond float64
}

// Modify run() to use the new values from .env:
cfg.httpPort = env.GetInt("HTTP_PORT")
cfg.db.dsn = env.GetString("DB_DSN")
cfg.apiTimeout = env.GetInt("API_TIMEOUT_SECONDS")
cfg.apiCallsAllowedPerSecond = float64(env.GetInt("API_CALLS_ALLOWED_PER_SECOND"))

// cfg.baseURL = env.GetString("BASE_URL") - not required

中间件和路由

样板已经有一个中间件可以从恐慌中恢复。我们将添加另外 3 个:Content-Type 检查、速率限制和 API 超时保护。

添加收费站库:

go get github.com/didip/tollbooth

更新

func (app *application) contentTypeCheck(next http.Handler) http.Handler {
 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  if r.Header.Get("Content-Type") != "application/json" {
   app.unsupportedMediaType(w, r)

   return
  }
  next.ServeHTTP(w, r)
 })
}


func (app *application) rateLimiter(next http.Handler) http.Handler {
 limiter := tollbooth.NewLimiter(app.config.apiCallsAllowedPerSecond, nil)
 limiter.SetIPLookups([]string{"X-Real-IP", "X-Forwarded-For", "RemoteAddr"})

 return tollbooth.LimitHandler(limiter, next)
}


func (app *application) apiTimeout(next http.Handler) http.Handler {
 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  timeoutDuration := time.Duration(app.config.apiTimeout) * time.Second

  ctx, cancel := context.WithTimeout(r.Context(), timeoutDuration)
  defer cancel()

  r = r.WithContext(ctx)

  done := make(chan struct{})

  go func() {
   next.ServeHTTP(w, r)
   close(done)
  }()

  select {
  case <-done:
   return
  case <-ctx.Done():
   app.gatewayTimeout(w, r)
   return
  }
 })
}

中间件需要添加到路由中。它们可以添加到所有路由,也可以添加到特定路由。在我们的例子中,仅 POST 请求需要 Content-Type 检查(即强制输入标头包含 Content-Type: application/json)。所以修改routes.go如下:

func (app *application) routes() http.Handler {
 mux := httprouter.New()

 mux.NotFound = http.HandlerFunc(app.notFound)
 mux.MethodNotAllowed = http.HandlerFunc(app.methodNotAllowed)

 // Serve the Swagger UI. Uncomment this line later
 // mux.Handler("GET", "/docs/*any", httpSwagger.WrapHandler)

 mux.HandlerFunc("GET", "/status", app.status)
 mux.HandlerFunc("GET", "/materia", app.getAllMateria)

 // Adding content-type check middleware to only the POST method
 mux.Handler("POST", "/fusion", app.contentTypeCheck(http.HandlerFunc(app.fuseMateria)))

 return app.chainMiddlewares(mux)
}

func (app *application) chainMiddlewares(next http.Handler) http.Handler {
 middlewares := []func(http.Handler) http.Handler{
  app.recoverPanic,
  app.apiTimeout,
  app.rateLimiter,
 }

 for _, middleware := range middlewares {
  next = middleware(next)
 }

 return next
}

错误处理

/api/errors.go 中添加以下方法来帮助中间件功能:

func (app *application) unsupportedMediaType(w http.ResponseWriter, r *http.Request) {
 message := fmt.Sprintf("The %s Content-Type is not supported", r.Header.Get("Content-Type"))
 app.errorMessage(w, r, http.StatusUnsupportedMediaType, message, nil)
}

func (app *application) gatewayTimeout(w http.ResponseWriter, r *http.Request) {
 message := "Request timed out"
 app.errorMessage(w, r, http.StatusGatewayTimeout, message, nil)
}

请求和响应结构文件

/api/dtos.go :

package main

// MateriaDTO provides Materia details - Name, Description and Type (Magic / Command / Support / Independent)
type MateriaDTO struct {
 Name        string `json:"name" example:"Thunder"`
 Type        string `json:"type" example:"Magic"`
 Description string `json:"description" example:"Shoots lightning forward dealing thunder damage."`
}

// StatusDTO provides status of the server
type StatusDTO struct {
 Status string `json:"Status" example:"OK"`
}

// ErrorResponseDTO provides Error message
type ErrorResponseDTO struct {
 Error string `json:"Error" example:"The server encountered a problem and could not process your request"`
}

/api/requests.go :

brew install postgresql@17

生成代码中的验证器稍后将用于验证融合端点的输入字段。

组合规则的数据结构

创建文件 /internal/crisis-core-materia-fusion/constants.go

添加以下内容:

# create the DB
createdb materiafusiondb
# step into the DB to perform SQL commands
psql materiafusiondb

32 种 MateriaType 的完整列表可以在此处找到。

创建文件 /internal/crisis-core-materia-fusion/models.go

添加以下内容:

-- create an SQL user to be used by the Go server
CREATE USER go_client WITH PASSWORD 'xxxxxxxx';

-- The Go server doesn't ever need to add data to the DB. 
-- So let's give it just read permission.
CREATE ROLE readonly_role;
GRANT USAGE ON SCHEMA public TO readonly_role;

-- This command gives SELECT access to all future created tables. 
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly_role;

-- If you want to be more strict and give access only to tables that already exist, use this:
-- GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_role;

GRANT readonly_role TO go_client;

完整的规则列表可以在这里找到。

api/handlers.go 中材质的处理程序

CREATE TYPE display_materia_type AS ENUM ('Magic', 'Command', 'Support', 'Independent');

CREATE TYPE materia_type AS ENUM ('Fire', 'Ice', 'Lightning', 'Restore', 'Full Cure', 'Status Defense', 'Defense', 'Absorb Magic', 'Status Magic', 'Fire & Status', 'Ice & Status', 'Lightning & Status', 'Gravity', 'Ultimate', 'Quick Attack', 'Quick Attack & Status', 'Blade Arts', 'Blade Arts & Status', 'Fire Blade', 'Ice Blade', 'Lightning Blade', 'Absorb Blade', 'Item', 'Punch', 'SP Turbo', 'HP Up', 'AP Up', 'ATK Up', 'VIT Up', 'MAG Up', 'SPR Up', 'Dash', 'Dualcast', 'DMW', 'Libra', 'MP Up', 'Anything');

CREATE TABLE materia (
    id integer NOT NULL,
    name character varying(50) NOT NULL,
    materia_type materia_type NOT NULL,
    grade integer NOT NULL,
    display_materia_type display_materia_type,
    description text
    CONSTRAINT materia_pkey PRIMARY KEY (id)
);

-- The primary key 'id' should auto-increment by 1 for every row entry.
CREATE SEQUENCE materia_id_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

ALTER SEQUENCE materia_id_seq OWNED BY materia.id;

ALTER TABLE ONLY materia ALTER COLUMN id SET DEFAULT nextval('materia_id_seq'::REGCLASS);

服务器内缓存

我们使用服务器内缓存,因为:

  1. 从数据库获取的数据永远不会改变。
  2. 材质和融合端点使用相同的数据。

更新main.go:

COPY materia(name,materia_type,grade,display_materia_type,description) FROM
 '<path_to_csv_file>/materiadata.csv' DELIMITER ',' CSV HEADER;

更新 api/helpers.go:

? codebase
├─ cmd
│  └─ api
│     ├─ errors.go
│     ├─ handlers.go
│     ├─ helpers.go
│     ├─ main.go
│     ├─ middleware.go
│     └─ server.go
├─ internal
│  ├─ database --- db.go
│  ├─ env --- env.go
│  ├─ request --- json.go
│  ├─ response --- json.go
│  └─ validator
│     ├─ helpers.go
│     └─ validators.go
├─ go.mod
├─ LICENSE
├─ Makefile
├─ README.md
└─ README.html

api/handlers.go 中的融合处理程序

HTTP_PORT=4444
DB_DSN=go_client:<password>@localhost:5432/materiafusiondb?sslmode=disable
API_TIMEOUT_SECONDS=5
API_CALLS_ALLOWED_PER_SECOND=1

完整的处理程序代码可以在这里找到。

Swagger UI 和 OpenAPI 定义文档

添加 Swagger 库:

go get github.com/joho/godotenv

在routes.go中取消注释Swagger行,并添加导入:

// At the beginning of main():
err := godotenv.Load(".env") // Loads environment variables from .env file
if err != nil { // This will be true in prod, but that's fine.
  fmt.Println("Error loading .env file")
}


// Modify config struct:
type config struct {
  baseURL string
  db      struct {
    dsn string
  }
  httpPort                 int
  apiTimeout               int
  apiCallsAllowedPerSecond float64
}

// Modify run() to use the new values from .env:
cfg.httpPort = env.GetInt("HTTP_PORT")
cfg.db.dsn = env.GetString("DB_DSN")
cfg.apiTimeout = env.GetInt("API_TIMEOUT_SECONDS")
cfg.apiCallsAllowedPerSecond = float64(env.GetInt("API_CALLS_ALLOWED_PER_SECOND"))

// cfg.baseURL = env.GetString("BASE_URL") - not required

在处理程序、DTO 和模型文件中,添加 Swagger 文档的注释。请参阅此了解所有选项。

在终端中,运行:

go get github.com/didip/tollbooth

这将创建一个 api/docs 文件夹,其中包含可用于 Go、JSON 和 YAML 的定义。

要测试它,请启动本地服务器并打开 http://localhost:4444/docs。


最终文件夹结构:

func (app *application) contentTypeCheck(next http.Handler) http.Handler {
 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  if r.Header.Get("Content-Type") != "application/json" {
   app.unsupportedMediaType(w, r)

   return
  }
  next.ServeHTTP(w, r)
 })
}


func (app *application) rateLimiter(next http.Handler) http.Handler {
 limiter := tollbooth.NewLimiter(app.config.apiCallsAllowedPerSecond, nil)
 limiter.SetIPLookups([]string{"X-Real-IP", "X-Forwarded-For", "RemoteAddr"})

 return tollbooth.LimitHandler(limiter, next)
}


func (app *application) apiTimeout(next http.Handler) http.Handler {
 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  timeoutDuration := time.Duration(app.config.apiTimeout) * time.Second

  ctx, cancel := context.WithTimeout(r.Context(), timeoutDuration)
  defer cancel()

  r = r.WithContext(ctx)

  done := make(chan struct{})

  go func() {
   next.ServeHTTP(w, r)
   close(done)
  }()

  select {
  case <-done:
   return
  case <-ctx.Done():
   app.gatewayTimeout(w, r)
   return
  }
 })
}

3. 在 CockroachDB 中设置远程 PostgreSQL 实例

  1. 使用此处的步骤。
  2. 创建证书后,在项目中创建 /certs/root.crt 并在其中添加证书。我们稍后将在 Google Run 配置中引用此文件。
  3. 警告!我们将此文件夹推送到远程存储库。将 certs/ 文件夹添加到 .gitignore。如果您愿意,我们在本地创建证书只是为了测试连接。
  4. 现在,当您转到 CockroachDB → 仪表板 → 左侧菜单 → 数据库时,您应该能够看到您创建的数据库。

迁移

从本地数据库实例中,运行:

brew install postgresql@17
  1. 转到 CockroachDB → 左侧菜单 → 迁移 → 添加架构 → 拖动刚刚获得的 SQL 文件。除表数据插入之外的所有步骤都将运行。它还会向您显示已执行的步骤列表。
  2. 在撰写本文时,CockroachDB 中的 PostgreSQL 实例不支持 IMPORT INTO 等语句。因此,我必须在本地 SQL 文件中创建 270 行的 INSERT 语句(我们可以从刚刚获得的 pg_dump 输出得出)。
  3. 登录远程实例,并运行SQL文件。

登录远程实例:

# create the DB
createdb materiafusiondb
# step into the DB to perform SQL commands
psql materiafusiondb

4. 部署 Google Cloud Run 实例

  1. 像这样创建一个 Dockerfile。
  2. 转到 Google Cloud Run 并为 API 创建一个新项目。
  3. 创建服务 → 从存储库持续部署使用云构建进行设置存储库提供程序 = Github → 选择您的存储库 → 构建类型 = Dockerfile → 保存。
  4. 身份验证 = 允许未经授权的调用
  5. 大多数默认值应该就可以了。
  6. 向下滚动至集装箱 → 集装箱港口 = 4444。
  7. 选择变量和秘密选项卡,然后添加与本地 .env 文件中相同的环境变量。

价值观:

  1. HTTP_PORT = 4444
  2. DB_DSN = ?sslmode=verify-full&sslrootcert=/app/certs/root.crt
  3. API_TIMEOUT_SECONDS = 5
  4. API_CALLS_ALLOWED_PER_SECOND = 1

使用 Google Secret Manager 获取证书

最后一块拼图。

  1. 搜索 Secret Manager → 创建 Secret → Name = ‘DB_CERT’ → 上传 CockroachDB 的 .crt 证书。
  2. 在 Cloud Run →(您的服务)→ 单击 编辑持续部署 → 向下滚动到配置 → 打开编辑器。
  3. 将此添加为第一步:
-- create an SQL user to be used by the Go server
CREATE USER go_client WITH PASSWORD 'xxxxxxxx';

-- The Go server doesn't ever need to add data to the DB. 
-- So let's give it just read permission.
CREATE ROLE readonly_role;
GRANT USAGE ON SCHEMA public TO readonly_role;

-- This command gives SELECT access to all future created tables. 
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly_role;

-- If you want to be more strict and give access only to tables that already exist, use this:
-- GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_role;

GRANT readonly_role TO go_client;

这将使 Cloud Build 在构建开始之前在我们的项目中创建文件 certs/root.crt,以便 Dockerfile 可以访问它,即使我们从未将其推送到我们的 Github 存储库。


就是这样。尝试推送提交并检查构建是否触发。 Cloud Run 仪表板将显示您托管的 Go 服务器的 URL。


有关“为什么你做了 X 而不是 Y?”的问题读这个。

对于您想了解或讨论的任何其他内容,请访问此处,或在下面发表评论。

以上是使用 Go、PostgreSQL、Google Cloud 和 CockroachDB 构建 API的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn