搜尋
首頁後端開發Golang使用 Gin、FerretDB 和 oapi-codegen 建立部落格 API

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
去編碼/二進制包:實踐示例去編碼/二進制包:實踐示例May 10, 2025 am 12:16 AM

theEncoding/binarypackageingoisessential forhandlingbinarydata,offeringFunctionStoreadAndWritedAtainBig-Endianandlittle-endianFormats.1)IT'SidealFornetwork-work-workprotocels,enableSeringSeringSerializationalializationalialization andDeSerialization andDeSerializationOfStructuredDatalizedDataliakePackackEtheadErloth

GO BYTES軟件包:您需要了解字節片的基本功能GO BYTES軟件包:您需要了解字節片的基本功能May 10, 2025 am 12:11 AM

theessentionfunctionsingo'sbytespackageThatyOuneedToknoware:1)字節.indexforsearchingwithinbyteslices,2)bytes.splitforparsing數據,3)字節。 joinforConcatenatingslices,4)bytes.containsforcheckingsubslicepresence和5)bytes.replaceallfordatatatatransformatio

GO中'字符串”包的替代方案是什麼?GO中'字符串”包的替代方案是什麼?May 10, 2025 am 12:09 AM

Gooffersalternativestothestringspackageforstringmanipulation:1)Theregexppackageforcomplexpatternmatching,2)Thestrconvpackagefornumericconversions,and3)Externallibrarieslikestrutilforspecializedoperations.Theseoptionscatertodifferentneeds,enhancingyou

GO編碼/二進制軟件包:處理不同的數據類型GO編碼/二進制軟件包:處理不同的數據類型May 10, 2025 am 12:09 AM

效率地使用/binarypackageforhandlingvariousdatatypes,lofterTheSesteps:1)指定bbyteorder(例如binary.littleendian)for -compatibility.2)usepututuint32/uint32222222222forintfloAtfloat32bits/floatt32bits/floatth32222222frolbomentss.3225frolbomtss.3)

掌握go bytes:深入研究'字節”軟件包掌握go bytes:深入研究'字節”軟件包May 10, 2025 am 12:09 AM

掌握bytes包的原因是它能显著提高处理字节切片的效率和性能。1)bytes包提供了强大的工具,如bytes.Contains用于搜索字节序列,2)bytes.Buffer类型适用于增量构建字节切片,3)了解bytes包的使用陷阱和性能优化策略,如重用bytes.Buffer实例,可以避免常见错误并提升效率。

學習GO String操縱:使用'字符串”軟件包學習GO String操縱:使用'字符串”軟件包May 09, 2025 am 12:07 AM

Go的"strings"包提供了豐富的功能,使字符串操作高效且簡單。 1)使用strings.Contains()檢查子串。 2)strings.Split()可用於解析數據,但需謹慎使用以避免性能問題。 3)strings.Join()適用於格式化字符串,但對小數據集,循環使用 =更有效。 4)對於大字符串,使用strings.Builder構建字符串更高效。

GO:使用標準'字符串”包的字符串操縱GO:使用標準'字符串”包的字符串操縱May 09, 2025 am 12:07 AM

Go語言使用"strings"包進行字符串操作。 1)拼接字符串使用strings.Join函數。 2)查找子串使用strings.Contains函數。 3)替換字符串使用strings.Replace函數,這些函數高效且易用,適用於各種字符串處理任務。

使用GO的'字節”軟件包掌握字節切片操作:實用指南使用GO的'字節”軟件包掌握字節切片操作:實用指南May 09, 2025 am 12:02 AM

資助bytespackageingoisesential foreffited byteSemanipulation,uperingFunctionsLikeContains,index,andReplaceForsearchingangingAndModifyingBinaryData.itenHancesperformanceNandCoderAceAnibility,MakeitiTavitalToolToolToolToolToolToolToolToolToolForhandLingBinaryData,networkProtocols,networkProtocoLss,networkProtocols,andetFilei

See all articles

熱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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境