찾다
백엔드 개발GolangGin, FerretDB 및 oapi-codegen을 사용하여 블로그 API 구축

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으로 문의하세요.
문자열 조작을 배우십시오 : '문자열'패키지로 작업하십시오문자열 조작을 배우십시오 : '문자열'패키지로 작업하십시오May 09, 2025 am 12:07 AM

Go의 "Strings"패키지는 문자열 작동 효율적이고 간단하게 만드는 풍부한 기능을 제공합니다. 1) STRINGS.CONTAINS ()를 사용하여 하위 문자열을 확인하십시오. 2) strings.split ()를 사용하여 데이터를 구문 분석 할 수 있지만 성능 문제를 피하기 위해주의해서 사용해야합니다. 3) strings.join ()은 문자열 서식에 적합하지만 작은 데이터 세트의 경우 루핑 =가 더 효율적입니다. 4) 큰 문자열의 경우 문자열을 사용하여 문자열을 만드는 것이 더 효율적입니다.

GO : 표준 '문자열'패키지를 사용한 문자열 조작GO : 표준 '문자열'패키지를 사용한 문자열 조작May 09, 2025 am 12:07 AM

Go는 문자열 작업에 "Strings"패키지를 사용합니다. 1) splice strings에 strings.join 기능을 사용하십시오. 2) 문자열을 사용하여 기능을 포함하여 하위 문자열을 찾으십시오. 3) 문자열을 사용하십시오. 이러한 기능은 효율적이고 사용하기 쉽고 다양한 문자열 처리 작업에 적합합니다.

Go의 '바이트'패키지로 마스터 링 바이트 슬라이스 조작 : 실용 가이드Go의 '바이트'패키지로 마스터 링 바이트 슬라이스 조작 : 실용 가이드May 09, 2025 am 12:02 AM

the byteSpackageOsestementialforeficientsliceManipulation, ontowerfunctionslikecececectains, index, andreplaceforsearching 및 modifyingbinaryData.ItenHancesBinaryData, MakingIvitalToolforHandlingBinaryData, NetworkProtocols 및 filei

Go Binary Encoding/Decoding : '인코딩/바이너리'패키지로 작업하십시오Go Binary Encoding/Decoding : '인코딩/바이너리'패키지로 작업하십시오May 08, 2025 am 12:13 AM

Go는 이진 인코딩 및 디코딩을 위해 "인코딩/이진"패키지를 사용합니다. 1)이 패키지는 binary.wart.write 및 binary.Read 기능을 작성하고 읽기 데이터를 제공합니다. 2) 올바른 엔디언 (예 : Bigendian 또는 Littleendian)을 선택하는 데주의를 기울이십시오. 3) 데이터 정렬 및 오류 처리도 데이터의 정확성과 성능을 보장하는 핵심입니다.

GO : 표준 '바이트'패키지가있는 바이트 슬라이스 조작GO : 표준 '바이트'패키지가있는 바이트 슬라이스 조작May 08, 2025 am 12:09 AM

"바이트"PackageOffersefficientFunctionSformanipulatingByteslices.1) audeBytes.joinforconcateNatingSlices, 2) bytes.bufferforIncrementalWriting, 3) bytes.indexorBytes.IndexByTeForsearching, 4) bytes.ReaderReadingInCunks, 및 5) thepliteTor

GO 인코딩/이진 패키지 : 이진 작업의 성능 최적화GO 인코딩/이진 패키지 : 이진 작업의 성능 최적화May 08, 2025 am 12:06 AM

theencoding/binarypackageingofectiveficizatebinaryoperationsduetoitssupportforendiannessandefficientdatahandling.toenhanceperformance : 1) usebinary.nativeBinary.nativeBinary.nativeBinary.nativeEndianFornativeendiannesstoavoidByteswapping.2) BatchReadandWriteOperationStoredUtei/over

바이트 패키지 : 짧은 참조 및 팁바이트 패키지 : 짧은 참조 및 팁May 08, 2025 am 12:05 AM

GO의 바이트 패키지는 주로 바이트 슬라이스를 효율적으로 처리하는 데 사용됩니다. 1) Bytes를 사용하여 Buffer는 불필요한 메모리 할당을 피하기 위해 스트링 스 플라이 싱을 효율적으로 수행 할 수 있습니다. 2) BYTES.Equal 함수는 바이트 슬라이스를 빠르게 비교하는 데 사용됩니다. 3) bytes.index, bytes.split 및 bytes.replaceall 함수를 사용하여 바이트 슬라이스를 검색하고 조작 할 수 있지만 성능 문제에주의를 기울여야합니다.

바이트 패키지를 이동하십시오 : 바이트 슬라이스 조작을위한 실제 예바이트 패키지를 이동하십시오 : 바이트 슬라이스 조작을위한 실제 예May 08, 2025 am 12:01 AM

바이트 패키지는 바이트 슬라이스를 효율적으로 처리하기위한 다양한 기능을 제공합니다. 1) 바이트 시퀀스를 확인하려면 바이트를 사용하십시오. 2) 바이트 슬라이스를 분할하려면 BYTES.SPLIT를 사용하십시오. 3) 바이트 시퀀스 바이트를 교체하십시오. 4) Bytes.join을 사용하여 여러 바이트 슬라이스를 연결하십시오. 5) Bytes.Buffer를 사용하여 데이터를 작성하십시오. 6) 오류 처리 및 데이터 검증을 위해 결합 된 바이트.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구