
作为一名软件工程师,我热衷于持续学习和技能提升,探索各种软件解决方案。我决定整合以下工具来构建一个新的API:
我从一个简单的用户模型开始,定义了OpenAPI规范:
<code class="yaml">components:
schemas:
user:
type: object
properties:
id:
type: string
example: 123
readonly: true
email:
type: string
example: me@example.com
writeonly: true
name:
type: string
example: alice</code>这个规范用于/users POST请求,返回201 (Created)状态码,并使用自定义JSON对象描述400 (Bad Request)错误。
我利用oapi-codegen工具,创建了tools.go文件(类似于项目仓库中的示例)。同时创建了internal/handlers/server.go文件:
<code class="go">//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=server.config.yaml ../../openapi.yaml //go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config=types.config.yaml ../../openapi.yaml package handlers</code>
server.config.yaml用于配置严格的net/http服务器,types.config.yaml用于生成模型代码。执行go mod init,go mod tidy和go generate ./...后,生成了大部分API启动所需的文件。
接下来,在server.go中添加以下代码,创建一个实现生成接口的服务器结构:
<code class="go">var _ strictserverinterface = (*server)(nil)
type server struct{}
func newserver() server {
return server{}
}</code>然后,在user.go中创建POST /users请求的处理程序:
<code class="go">func (*Server) PostUser(ctx context.Context, request PostUserRequestObject) (PostUserResponseObject, error) {
return nil, nil
}</code>目前返回nil,因为我正在开发user_test.go文件,使用Testify编写测试用例,并定义POST /users的行为。由于数据库尚未连接,响应将是硬编码的结构,以确保测试通过。
在接下来的博客文章中,我将继续构建main.go和Dockerfile来启动服务器,并集成Codecov到代码仓库中。 完整的代码可在以下仓库中找到:https://www.php.cn/link/f5f699f14ef1279e76bc576c0459b25a
以上就是构建和部署新 API(第 1 部分)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号