>  기사  >  백엔드 개발  >  Gin, FerretDB 및 oapi-codegen을 사용하여 블로그 API 구축

Gin, FerretDB 및 oapi-codegen을 사용하여 블로그 API 구축

WBOY
WBOY원래의
2024-09-05 22:34:03165검색

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

이 튜토리얼에서는 Go를 사용하여 간단한 블로그 애플리케이션용 RESTful API를 만드는 과정을 안내합니다. 우리는 다음 기술을 사용할 것입니다:

  1. Gin: Go용 웹 프레임워크
  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 파일을 생성합니다.

데이터베이스 계층 구현

FerretDB를 사용하여 데이터베이스 계층을 구현하려면 db/db.go라는 새 파일을 생성하세요.

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 핸들러 구현

API 핸들러를 구현하려면 handlers/handlers.go라는 새 파일을 생성하세요.

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가 실행되었으므로 컬 명령을 사용하여 테스트해 보겠습니다.

  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를 프로덕션 환경에 배포하기 전에 오류를 적절하게 처리하고, 적절한 로깅을 추가하고, 보안 조치를 구현해야 합니다.


도움이 필요하신가요?

어려운 문제에 직면했거나 새로운 아이디어나 프로젝트에 대한 외부 관점이 필요합니까? 제가 도와드릴 수 있어요! 대규모 투자를 하기 전에 기술 개념 증명을 구축하려는 경우나 어려운 문제에 대한 지침이 필요한 경우 제가 도와드리겠습니다.

제공되는 서비스:

  • 문제 해결: 혁신적인 솔루션으로 복잡한 문제를 해결합니다.
  • 상담: 프로젝트에 대한 전문가의 조언과 신선한 관점을 제공합니다.
  • 개념 증명: 아이디어를 테스트하고 검증하기 위한 예비 모델 개발

저와 함께 일하는 데 관심이 있으시면 hangaikevin@gmail.com으로 이메일을 보내주세요.

당신의 도전을 기회로 바꾸세요!

위 내용은 Gin, FerretDB 및 oapi-codegen을 사용하여 블로그 API 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.