当前位置:首页 > 文章列表 > Golang > Go教程 > 使用 Gin、FerretDB 和 oapi-codegen 构建博客 API

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

来源:dev.to 2024-09-09 23:24:55 0浏览 收藏
推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《使用 Gin、FerretDB 和 oapi-codegen 构建博客 API》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

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

在本教程中,我们将逐步介绍使用 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》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
在 C# 和 JavaScript 之间选择进行网页抓取在 C# 和 JavaScript 之间选择进行网页抓取
上一篇
在 C# 和 JavaScript 之间选择进行网页抓取
京东方发布新一代 ADS Pro+MLED 背光显示解决方案,支持 500Hz 刷新率、1000nits + 全屏亮度
下一篇
京东方发布新一代 ADS Pro+MLED 背光显示解决方案,支持 500Hz 刷新率、1000nits + 全屏亮度
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    543次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    516次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    500次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    485次学习
查看更多
AI推荐
  • ChatExcel酷表:告别Excel难题,北大团队AI助手助您轻松处理数据
    ChatExcel酷表
    ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
    3358次使用
  • Any绘本:开源免费AI绘本创作工具深度解析
    Any绘本
    探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
    3568次使用
  • 可赞AI:AI驱动办公可视化智能工具,一键高效生成文档图表脑图
    可赞AI
    可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
    3600次使用
  • 星月写作:AI网文创作神器,助力爆款小说速成
    星月写作
    星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
    4724次使用
  • MagicLight.ai:叙事驱动AI动画视频创作平台 | 高效生成专业级故事动画
    MagicLight
    MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
    3973次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码