”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 Gin、FerretDB 和 oapi-codegen 构建博客 API

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

发布于2024-10-31
浏览:255

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

In this tutorial, we’ll walk through the process of creating a RESTful API for a simple blog application using Go. We’ll be using the following technologies:

  1. Gin: A web framework for Go
  2. FerretDB: A MongoDB-compatible database
  3. oapi-codegen: A tool for generating Go server boilerplate from OpenAPI 3.0 specifications

Table of Contents

  1. Setting Up the Project
  2. Defining the API Specification
  3. Generating Server Code
  4. Implementing the Database Layer
  5. Implementing the API Handlers
  6. Running the Application
  7. Testing the API
  8. Conclusion

Setting Up the Project

First, let’s set up our Go project and install the necessary dependencies:

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

Defining the API Specification

Create a file named api.yaml in your project root and define the OpenAPI 3.0 specification for our blog API:

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

Generating Server Code

Now, let’s use oapi-codegen to generate the server code based on our API specification:

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

This command will create a new directory called api and generate the api.go file containing the server interfaces and models.

Implementing the Database Layer

Create a new file called db/db.go to implement the database layer using 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
}

Implementing the API Handlers

Create a new file called handlers/handlers.go to implement the API handlers:

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)
}

Running the Application

Create a new file called main.go in the project root to set up and run the application:

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)
    }
}

Testing the API

Now that we have our API up and running, let’s test it using curl commands:

  1. Create a new post:
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. List all posts:
curl http://localhost:8080/posts

  1. Get a specific post (replace {id} with the actual post ID):
curl http://localhost:8080/posts/{id}

  1. Update a post (replace {id} with the actual post 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. Delete a post (replace {id} with the actual post ID):
curl -X DELETE http://localhost:8080/posts/{id}

Conclusion

In this tutorial, we’ve built a simple blog API using the Gin framework, FerretDB, and oapi-codegen. We’ve covered the following steps:

  1. Setting up the project and installing dependencies
  2. Defining the API specification using OpenAPI 3.0
  3. Generating server code with oapi-codegen
  4. Implementing the database layer using FerretDB
  5. Implementing the API handlers
  6. Running the application
  7. Testing the API with curl commands

This project demonstrates how to create a RESTful API with Go, leveraging the power of code generation and a MongoDB-compatible database. You can further extend this API by adding authentication, pagination, and more complex querying capabilities.

Remember to handle errors appropriately, add proper logging, and implement security measures before deploying this API to a production environment.


Need Help?

Are you facing challenging problems, or need an external perspective on a new idea or project? I can help! Whether you're looking to build a technology proof of concept before making a larger investment, or you need guidance on difficult issues, I'm here to assist.

Services Offered:

  • Problem-Solving: Tackling complex issues with innovative solutions.
  • Consultation: Providing expert advice and fresh viewpoints on your projects.
  • Proof of Concept: Developing preliminary models to test and validate your ideas.

If you're interested in working with me, please reach out via email at [email protected].

Let's turn your challenges into opportunities!

版本声明 本文转载于:https://dev.to/hungai/building-a-blog-api-with-gin-ferretdb-and-oapi-codegen-30o9?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    The Mystery of "Broken" Two-Phase Template Instantiation in Microsoft Visual C Problem Statement:Users commonly express concerns that Micro...
    编程 发布于2025-03-12
  • UTF-8 vs. Latin-1:字符编码大揭秘!
    UTF-8 vs. Latin-1:字符编码大揭秘!
    [utf-8和latin1 在他们的应用中,出现了一个基本问题:什么辨别特征区分了这两个编码?超出其字符表现能力,UTF-8具有额外的几个优势。从历史上看,MySQL对UTF-8的支持仅限于每个字符的三个字节,这阻碍了基本多语言平面(BMP)之外的字符的表示。但是,随着MySQL 5.5的出现,...
    编程 发布于2025-03-12
  • 大批
    大批
    [2 数组是对象,因此它们在JS中也具有方法。 切片(开始):在新数组中提取部分数组,而无需突变原始数组。 令ARR = ['a','b','c','d','e']; // USECASE:提取直到索引作...
    编程 发布于2025-03-12
  • 如何在Java字符串中有效替换多个子字符串?
    如何在Java字符串中有效替换多个子字符串?
    在java 中有效地替换多个substring,需要在需要替换一个字符串中的多个substring的情况下,很容易求助于重复应用字符串的刺激力量。 However, this can be inefficient for large strings or when working with nu...
    编程 发布于2025-03-12
  • Part SQL注入系列:高级SQL注入技巧详解
    Part SQL注入系列:高级SQL注入技巧详解
    [2 Waymap pentesting工具:单击此处 trixsec github:单击此处 trixsec电报:单击此处 高级SQL注入利用 - 第7部分:尖端技术和预防 欢迎参与我们SQL注入系列的第7部分!该分期付款将攻击者采用的高级SQL注入技术 1。高...
    编程 发布于2025-03-12
  • 为什么PYTZ最初显示出意外的时区偏移?
    为什么PYTZ最初显示出意外的时区偏移?
    与pytz 最初从pytz获得特定的偏移。例如,亚洲/hong_kong最初显示一个七个小时37分钟的偏移: 差异源利用本地化将时区分配给日期,使用了适当的时区名称和偏移量。但是,直接使用DateTime构造器分配时区不允许进行正确的调整。 example pytz.timezone(...
    编程 发布于2025-03-12
  • 如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    How to Resolve "General error: 2006 MySQL server has gone away" While Inserting RecordsIntroduction:Inserting data into a MySQL database can...
    编程 发布于2025-03-12
  • 我们如何保护有关恶意内容的文件上传?
    我们如何保护有关恶意内容的文件上传?
    对文件上载上传到服务器的安全性问题可以引入重大的安全风险,因为用户可能会提供潜在的恶意内容。了解这些威胁并实施有效的缓解策略对于维持应用程序的安全性至关重要。用户可以将文件名操作以绕过安全措施。避免将其用于关键目的或使用其原始名称保存文件。用户提供的MIME类型可能不可靠。使用服务器端检查确定实际...
    编程 发布于2025-03-12
  • 如何使用JavaScript中的正则表达式从字符串中删除线路断裂?
    如何使用JavaScript中的正则表达式从字符串中删除线路断裂?
    在此代码方案中删除从字符串在JavaScript中解决此问题,根据操作系统的编码,对线断裂的识别不同。 Windows使用“ \ r \ n”序列,Linux采用“ \ n”,Apple系统使用“ \ r。” 来满足各种线路断裂的变化,可以使用以下正则表达式: [&& && &&&&&&&&&&&...
    编程 发布于2025-03-12
  • 为什么使用Firefox后退按钮时JavaScript执行停止?
    为什么使用Firefox后退按钮时JavaScript执行停止?
    导航历史记录问题:JavaScript使用Firefox Back Back 此行为是由浏览器缓存JavaScript资源引起的。要解决此问题并确保在后续页面访问中执行脚本,Firefox用户应设置一个空功能。 警报'); }; alert('inline Alert')...
    编程 发布于2025-03-12
  • 如何使用PHP将斑点(图像)正确插入MySQL?
    如何使用PHP将斑点(图像)正确插入MySQL?
    essue VALUES('$this->image_id','file_get_contents($tmp_image)')";This code builds a string in PHP, but the function call ...
    编程 发布于2025-03-12
  • 我可以将加密从McRypt迁移到OpenSSL,并使用OpenSSL迁移MCRYPT加密数据?
    我可以将加密从McRypt迁移到OpenSSL,并使用OpenSSL迁移MCRYPT加密数据?
    将我的加密库从mcrypt升级到openssl 问题:是否可以将我的加密库从McRypt升级到OpenSSL?如果是这样,如何?答案:是的,可以将您的Encryption库从McRypt升级到OpenSSL。可以使用openssl。附加说明: [openssl_decrypt()函数要求iv参...
    编程 发布于2025-03-12
  • 在Java中使用for-to-loop和迭代器进行收集遍历之间是否存在性能差异?
    在Java中使用for-to-loop和迭代器进行收集遍历之间是否存在性能差异?
    For Each Loop vs. Iterator: Efficiency in Collection TraversalIntroductionWhen traversing a collection in Java, the choice arises between using a for-...
    编程 发布于2025-03-12
  • 如何检查对象是否具有Python中的特定属性?
    如何检查对象是否具有Python中的特定属性?
    方法来确定对象属性存在寻求一种方法来验证对象中特定属性的存在。考虑以下示例,其中尝试访问不确定属性会引起错误: >>> a = someClass() >>> A.property Trackback(最近的最新电话): 文件“ ”,第1行, AttributeError: SomeClass...
    编程 发布于2025-03-12
  • Java HashSet/LinkedHashSet随机元素获取方法详解
    Java HashSet/LinkedHashSet随机元素获取方法详解
    在编程中找到一个随机元素,在编程中找到一个随机元素,从集合(例如集合)中选择一个随机元素很有用。 Java提供了多种类型的集合,包括障碍物和链接HASHSET。本文将探讨如何从这些特定集合实现的过程中选择一个随机元素。的java的hashset和linkedhashset a HashSet代表...
    编程 发布于2025-03-12

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3