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

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

Oct 24, 2024 am 07:02 AM

我使用 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

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Debian OpenSSL有哪些漏洞 Debian OpenSSL有哪些漏洞 Apr 02, 2025 am 07:30 AM

OpenSSL,作为广泛应用于安全通信的开源库,提供了加密算法、密钥和证书管理等功能。然而,其历史版本中存在一些已知安全漏洞,其中一些危害极大。本文将重点介绍Debian系统中OpenSSL的常见漏洞及应对措施。DebianOpenSSL已知漏洞:OpenSSL曾出现过多个严重漏洞,例如:心脏出血漏洞(CVE-2014-0160):该漏洞影响OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻击者可利用此漏洞未经授权读取服务器上的敏感信息,包括加密密钥等。

从前端转型后端开发,学习Java还是Golang更有前景? 从前端转型后端开发,学习Java还是Golang更有前景? Apr 02, 2025 am 09:12 AM

后端学习路径:从前端转型到后端的探索之旅作为一名从前端开发转型的后端初学者,你已经有了nodejs的基础,...

Beego ORM中如何指定模型关联的数据库? Beego ORM中如何指定模型关联的数据库? Apr 02, 2025 pm 03:54 PM

在BeegoORM框架下,如何指定模型关联的数据库?许多Beego项目需要同时操作多个数据库。当使用Beego...

Go语言中用于浮点数运算的库有哪些? Go语言中用于浮点数运算的库有哪些? Apr 02, 2025 pm 02:06 PM

Go语言中用于浮点数运算的库介绍在Go语言(也称为Golang)中,进行浮点数的加减乘除运算时,如何确保精度是�...

Go的爬虫Colly中Queue线程的问题是什么? Go的爬虫Colly中Queue线程的问题是什么? Apr 02, 2025 pm 02:09 PM

Go爬虫Colly中的Queue线程问题探讨在使用Go语言的Colly爬虫库时,开发者常常会遇到关于线程和请求队列的问题。�...

GoLand中自定义结构体标签不显示怎么办? GoLand中自定义结构体标签不显示怎么办? Apr 02, 2025 pm 05:09 PM

GoLand中自定义结构体标签不显示怎么办?在使用GoLand进行Go语言开发时,很多开发者会遇到自定义结构体标签在�...

在Go语言中使用Redis Stream实现消息队列时,如何解决user_id类型转换问题? 在Go语言中使用Redis Stream实现消息队列时,如何解决user_id类型转换问题? Apr 02, 2025 pm 04:54 PM

Go语言中使用RedisStream实现消息队列时类型转换问题在使用Go语言与Redis...

在 Go 语言中,为什么使用 Println 和 string() 函数打印字符串会出现不同的效果? 在 Go 语言中,为什么使用 Println 和 string() 函数打印字符串会出现不同的效果? Apr 02, 2025 pm 02:03 PM

Go语言中字符串打印的区别:使用Println与string()函数的效果差异在Go...

See all articles