首页 后端开发 Golang 使用 Gin、FerretDB 和 oapi-codegen 构建博客 API

使用 Gin、FerretDB 和 oapi-codegen 构建博客 API

Sep 05, 2024 pm 10:34 PM

Building a Blog API with Gin, FerretDB, and oapi-codegen

在本教程中,我们将逐步介绍使用 Go 为简单博客应用程序创建 RESTful API 的过程。我们将使用以下技术:

  1. Gin:Go 的 Web 框架
  2. FerretDB:兼容 MongoDB 的数据库
  3. oapi-codegen:根据 OpenAPI 3.0 规范生成 Go 服务器样板的工具

目录

  1. 设置项目
  2. 定义 API 规范
  3. 生成服务器代码
  4. 实现数据库层
  5. 实现 API 处理程序
  6. 运行应用程序
  7. 测试 API
  8. 结论

设置项目

首先,让我们设置 Go 项目并安装必要的依赖项:

mkdir blog-api
cd blog-api
go mod init github.com/yourusername/blog-api
go get github.com/gin-gonic/gin
go get github.com/deepmap/oapi-codegen/cmd/oapi-codegen
go get github.com/FerretDB/FerretDB

定义API规范

在项目根目录中创建一个名为 api.yaml 的文件,并为我们的博客 API 定义 OpenAPI 3.0 规范:

openapi: 3.0.0
info:
  title: Blog API
  version: 1.0.0
paths:
  /posts:
    get:
      summary: List all posts
      responses:
        '200':
          description: Successful response
          content:
            application/json:    
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Post'
    post:
      summary: Create a new post
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/NewPost'
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Post'
  /posts/{id}:
    get:
      summary: Get a post by ID
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Post'
    put:
      summary: Update a post
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/NewPost'
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Post'
    delete:
      summary: Delete a post
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
      responses:
        '204':
          description: Successful response

components:
  schemas:
    Post:
      type: object
      properties:
        id:
          type: string
        title:
          type: string
        content:
          type: string
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    NewPost:
      type: object
      required:
        - title
        - content
      properties:
        title:
          type: string
        content:
          type: string

生成服务器代码

现在,让我们使用 oapi-codegen 根据我们的 API 规范生成服务器代码:

oapi-codegen -package api api.yaml > api/api.go

此命令将创建一个名为 api 的新目录,并生成包含服务器接口和模型的 api.go 文件。

实施数据库层

创建一个名为 db/db.go 的新文件,以使用 FerretDB 实现数据库层:

package db

import (
    "context"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type Post struct {
    ID primitive.ObjectID `bson:"_id,omitempty"`
    Title string `bson:"title"`
    Content string `bson:"content"`
    CreatedAt time.Time `bson:"createdAt"`
    UpdatedAt time.Time `bson:"updatedAt"`
}

type DB struct {
    client *mongo.Client
    posts *mongo.Collection
}

func NewDB(uri string) (*DB, error) {
    client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(uri))
    if err != nil {
        return nil, err
    }

    db := client.Database("blog")
    posts := db.Collection("posts")

    return &DB{
        client: client,
        posts: posts,
    }, nil
}

func (db *DB) Close() error {
    return db.client.Disconnect(context.Background())
}

func (db *DB) CreatePost(title, content string) (*Post, error) {
    post := &Post{
        Title: title,
        Content: content,
        CreatedAt: time.Now(),
        UpdatedAt: time.Now(),
    }

    result, err := db.posts.InsertOne(context.Background(), post)
    if err != nil {
        return nil, err
    }

    post.ID = result.InsertedID.(primitive.ObjectID)
    return post, nil
}

func (db *DB) GetPost(id string) (*Post, error) {
    objectID, err := primitive.ObjectIDFromHex(id)
    if err != nil {
        return nil, err
    }

    var post Post
    err = db.posts.FindOne(context.Background(), bson.M{"_id": objectID}).Decode(&post)
    if err != nil {
        return nil, err
    }

    return &post, nil
}

func (db *DB) UpdatePost(id, title, content string) (*Post, error) {
    objectID, err := primitive.ObjectIDFromHex(id)
    if err != nil {
        return nil, err
    }

    update := bson.M{
        "$set": bson.M{
            "title": title,
            "content": content,
            "updatedAt": time.Now(),
        },
    }

    var post Post
    err = db.posts.FindOneAndUpdate(
        context.Background(),
        bson.M{"_id": objectID},
        update,
        options.FindOneAndUpdate().SetReturnDocument(options.After),
    ).Decode(&post)

    if err != nil {
        return nil, err
    }

    return &post, nil
}

func (db *DB) DeletePost(id string) error {
    objectID, err := primitive.ObjectIDFromHex(id)
    if err != nil {
        return err
    }

    _, err = db.posts.DeleteOne(context.Background(), bson.M{"_id": objectID})
    return err
}

func (db *DB) ListPosts() ([]*Post, error) {
    cursor, err := db.posts.Find(context.Background(), bson.M{})
    if err != nil {
        return nil, err
    }
    defer cursor.Close(context.Background())

    var posts []*Post
    for cursor.Next(context.Background()) {
        var post Post
        if err := cursor.Decode(&post); err != nil {
            return nil, err
        }
        posts = append(posts, &post)
    }

    return posts, nil
}

实施 API 处理程序

创建一个名为 handlers/handlers.go 的新文件来实现 API 处理程序:

package handlers

import (
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
    "github.com/yourusername/blog-api/api"
    "github.com/yourusername/blog-api/db"
)

type BlogAPI struct {
    db *db.DB
}

func NewBlogAPI(db *db.DB) *BlogAPI {
    return &BlogAPI{db: db}
}

func (b *BlogAPI) ListPosts(c *gin.Context) {
    posts, err := b.db.ListPosts()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    apiPosts := make([]api.Post, len(posts))
    for i, post := range posts {
        apiPosts[i] = api.Post{
            Id: post.ID.Hex(),
            Title: post.Title,
            Content: post.Content,
            CreatedAt: post.CreatedAt,
            UpdatedAt: post.UpdatedAt,
        }
    }

    c.JSON(http.StatusOK, apiPosts)
}

func (b *BlogAPI) CreatePost(c *gin.Context) {
    var newPost api.NewPost
    if err := c.ShouldBindJSON(&newPost); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    post, err := b.db.CreatePost(newPost.Title, newPost.Content)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusCreated, api.Post{
        Id: post.ID.Hex(),
        Title: post.Title,
        Content: post.Content,
        CreatedAt: post.CreatedAt,
        UpdatedAt: post.UpdatedAt,
    })
}

func (b *BlogAPI) GetPost(c *gin.Context) {
    id := c.Param("id")
    post, err := b.db.GetPost(id)
    if err != nil {
        c.JSON(http.StatusNotFound, gin.H{"error": "Post not found"})
        return
    }

    c.JSON(http.StatusOK, api.Post{
        Id: post.ID.Hex(),
        Title: post.Title,
        Content: post.Content,
        CreatedAt: post.CreatedAt,
        UpdatedAt: post.UpdatedAt,
    })
}

func (b *BlogAPI) UpdatePost(c *gin.Context) {
    id := c.Param("id")
    var updatePost api.NewPost
    if err := c.ShouldBindJSON(&updatePost); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    post, err := b.db.UpdatePost(id, updatePost.Title, updatePost.Content)
    if err != nil {
        c.JSON(http.StatusNotFound, gin.H{"error": "Post not found"})
        return
    }

    c.JSON(http.StatusOK, api.Post{
        Id: post.ID.Hex(),
        Title: post.Title,
        Content: post.Content,
        CreatedAt: post.CreatedAt,
        UpdatedAt: post.UpdatedAt,
    })
}

func (b *BlogAPI) DeletePost(c *gin.Context) {
    id := c.Param("id")
    err := b.db.DeletePost(id)
    if err != nil {
        c.JSON(http.StatusNotFound, gin.H{"error": "Post not found"})
        return
    }

    c.Status(http.StatusNoContent)
}

运行应用程序

在项目根目录中创建一个名为 main.go 的新文件来设置和运行应用程序:

package main

import (
    "log"

    "github.com/gin-gonic/gin"
    "github.com/yourusername/blog-api/api"
    "github.com/yourusername/blog-api/db"
    "github.com/yourusername/blog-api/handlers"
)

func main() {
    // Initialize the database connection
    database, err := db.NewDB("mongodb://localhost:27017")
    if err != nil {
        log.Fatalf("Failed to connect to the database: %v", err)
    }
    defer database.Close()

    // Create a new Gin router
    router := gin.Default()

    // Initialize the BlogAPI handlers
    blogAPI := handlers.NewBlogAPI(database)

    // Register the API routes
    api.RegisterHandlers(router, blogAPI)

    // Start the server
    log.Println("Starting server on :8080")
    if err := router.Run(":8080"); err != nil {
        log.Fatalf("Failed to start server: %v", err)
    }
}

测试 API

现在我们已经启动并运行了 API,让我们使用curl 命令来测试它:

  1. 创建一个新帖子:
curl -X POST -H "Content-Type: application/json" -d '{"title":"My First Post","content":"This is the content of my first post."}' http://localhost:8080/posts

  1. 列出所有帖子:
curl http://localhost:8080/posts

  1. 获取特定帖子(将 {id} 替换为实际帖子 ID):
curl http://localhost:8080/posts/{id}

  1. 更新帖子(将 {id} 替换为实际帖子 ID):
curl -X PUT -H "Content-Type: application/json" -d '{"title":"Updated Post","content":"This is the updated content."}' http://localhost:8080/posts/{id}

  1. 删除帖子(将 {id} 替换为实际帖子 ID):
curl -X DELETE http://localhost:8080/posts/{id}

结论

在本教程中,我们使用 Gin 框架、FerretDB 和 oapi-codegen 构建了一个简单的博客 API。我们已经介绍了以下步骤:

  1. 设置项目并安装依赖项
  2. 使用 OpenAPI 3.0 定义 API 规范
  3. 使用 oapi-codegen 生成服务器代码
  4. 使用FerretDB实现数据库层
  5. 实现 API 处理程序
  6. 运行应用程序
  7. 使用curl命令测试API

该项目演示了如何利用代码生成和 MongoDB 兼容数据库的强大功能,使用 Go 创建 RESTful API。您可以通过添加身份验证、分页和更复杂的查询功能来进一步扩展此 API。

请记住在将此 API 部署到生产环境之前适当处理错误、添加适当的日志记录并实施安全措施。


需要帮助吗?

您是否面临着具有挑战性的问题,或者需要外部视角来看待新想法或项目?我可以帮忙!无论您是想在进行更大投资之前建立技术概念验证,还是需要解决困难问题的指导,我都会为您提供帮助。

提供的服务:

  • 解决问题:通过创新的解决方案解决复杂问题。
  • 咨询:为您的项目提供专家建议和新观点。
  • 概念验证:开发初步模型来测试和验证您的想法。

如果您有兴趣与我合作,请通过电子邮件与我联系:hungaikevin@gmail.com。

让我们将挑战转化为机遇!

以上是使用 Gin、FerretDB 和 oapi-codegen 构建博客 API的详细内容。更多信息请关注PHP中文网其他相关文章!

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

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

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)

热门话题

PHP教程
1587
276
以身作则http中间件记录示例 以身作则http中间件记录示例 Aug 03, 2025 am 11:35 AM

Go中的HTTP日志中间件可记录请求方法、路径、客户端IP和耗时,1.使用http.HandlerFunc包装处理器,2.在调用next.ServeHTTP前后记录开始时间和结束时间,3.通过r.RemoteAddr和X-Forwarded-For头获取真实客户端IP,4.利用log.Printf输出请求日志,5.将中间件应用于ServeMux实现全局日志记录,完整示例代码已验证可运行,适用于中小型项目起步,扩展建议包括捕获状态码、支持JSON日志和请求ID追踪。

以身例子从stdin中读取 以身例子从stdin中读取 Jul 27, 2025 am 04:15 AM

使用fmt.Scanf可读取格式化输入,适合简单结构化数据,但字符串遇空格截止;2.推荐使用bufio.Scanner逐行读取,支持多行输入、EOF检测和管道输入,并可处理扫描错误;3.使用io.ReadAll(os.Stdin)一次性读取全部输入,适用于处理大块数据或文件流;4.实时按键响应需第三方库如golang.org/x/term,常规场景使用bufio已足够;实际建议:交互式简单输入用fmt.Scan,行输入或管道用bufio.Scanner,大块数据用io.ReadAll,且始终处理

Switch语句如何运行? Switch语句如何运行? Jul 30, 2025 am 05:11 AM

Go的switch语句默认不会贯穿执行,匹配到第一个条件后自动退出。1.switch以关键字开始并可带一个值或不带值;2.case按顺序从上到下匹配,仅运行第一个匹配项;3.可通过逗号列出多个条件来匹配同一case;4.不需要手动添加break,但可用fallthrough强制贯穿;5.default用于未匹配到的情况,通常放最后。

以身作则 以身作则 Jul 29, 2025 am 04:10 AM

Go泛型从1.18开始支持,用于编写类型安全的通用代码。1.泛型函数PrintSlice[Tany](s[]T)可打印任意类型切片,如[]int或[]string。2.通过类型约束Number限制T为int、float等数字类型,实现Sum[TNumber](slice[]T)T安全求和。3.泛型结构体typeBox[Tany]struct{ValueT}可封装任意类型值,配合NewBox[Tany](vT)*Box[T]构造函数使用。4.为Box[T]添加Set(vT)和Get()T方法,无需

将GO与Kafka集成以进行流数据 将GO与Kafka集成以进行流数据 Jul 26, 2025 am 08:17 AM

Go与Kafka集成是构建高性能实时数据系统的有效方案,应根据需求选择合适的客户端库:1.优先使用kafka-go以获得简洁的Go风格API和良好的context支持,适合快速开发;2.在需要精细控制或高级功能时选用Sarama;3.实现生产者时需配置正确的Broker地址、主题和负载均衡策略,并通过context管理超时与关闭;4.消费者应使用消费者组实现可扩展性和容错,自动提交偏移量并合理使用并发处理;5.使用JSON、Avro或Protobuf进行序列化,推荐结合SchemaRegistr

GO应用程序的标准项目布局是什么? GO应用程序的标准项目布局是什么? Aug 02, 2025 pm 02:31 PM

答案是:Go应用没有强制项目布局,但社区普遍采用一种标准结构以提升可维护性和扩展性。1.cmd/存放程序入口,每个子目录对应一个可执行文件,如cmd/myapp/main.go;2.internal/存放私有代码,不可被外部模块导入,用于封装业务逻辑和服务;3.pkg/存放可公开复用的库,供其他项目导入;4.api/可选,存放OpenAPI、Protobuf等API定义文件;5.config/、scripts/、web/分别存放配置文件、脚本和Web资源;6.根目录包含go.mod和go.sum

如何从GO中筑巢的循环中断 如何从GO中筑巢的循环中断 Jul 29, 2025 am 01:58 AM

在Go中,要跳出嵌套循环,应使用标签化break语句或通过函数返回;1.使用标签化break:将标签置于外层循环前,如OuterLoop:for{...},在内层循环中使用breakOuterLoop即可直接退出外层循环;2.将嵌套循环放入函数中,满足条件时用return提前返回,从而终止所有循环;3.避免使用标志变量或goto,前者冗长易错,后者非推荐做法;正确做法是标签必须位于循环之前而非之后,这是Go语言中跳出多层循环的惯用方式。

使用上下文软件包进行取消和超时 使用上下文软件包进行取消和超时 Jul 29, 2025 am 04:08 AM

USECONTEXTTOPROPAGATECELLATION ANDDEADEADLINESACROSSGOROUTINES,ENABLINGCOOPERATIVECELLATIONININHTTPSERVERS,背景任务,andChainedCalls.2.withContext.withContext.withCancel(),CreatseAcancellableBableBablebableBableBableBablebableContExtandAndCandExtandCallCallCancelLcancel()

See all articles