찾다
백엔드 개발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으로 문의하세요.
Debian Openssl의 취약점은 무엇입니까?Debian Openssl의 취약점은 무엇입니까?Apr 02, 2025 am 07:30 AM

보안 통신에 널리 사용되는 오픈 소스 라이브러리로서 OpenSSL은 암호화 알고리즘, 키 및 인증서 관리 기능을 제공합니다. 그러나 역사적 버전에는 알려진 보안 취약점이 있으며 그 중 일부는 매우 유해합니다. 이 기사는 데비안 시스템의 OpenSSL에 대한 일반적인 취약점 및 응답 측정에 중점을 둘 것입니다. DebianopensSL 알려진 취약점 : OpenSSL은 다음과 같은 몇 가지 심각한 취약점을 경험했습니다. 심장 출혈 ​​취약성 (CVE-2014-0160) :이 취약점은 OpenSSL 1.0.1 ~ 1.0.1F 및 1.0.2 ~ 1.0.2 베타 버전에 영향을 미칩니다. 공격자는이 취약점을 사용하여 암호화 키 등을 포함하여 서버에서 무단 읽기 민감한 정보를 사용할 수 있습니다.

PPROF 도구를 사용하여 GO 성능을 분석하는 방법은 무엇입니까?PPROF 도구를 사용하여 GO 성능을 분석하는 방법은 무엇입니까?Mar 21, 2025 pm 06:37 PM

이 기사는 프로파일 링 활성화, 데이터 수집 및 CPU 및 메모리 문제와 같은 일반적인 병목 현상을 식별하는 등 GO 성능 분석을 위해 PPROF 도구를 사용하는 방법을 설명합니다.

GO에서 단위 테스트를 어떻게 작성합니까?GO에서 단위 테스트를 어떻게 작성합니까?Mar 21, 2025 pm 06:34 PM

이 기사는 GO에서 단위 테스트 작성, 모범 사례, 조롱 기술 및 효율적인 테스트 관리를위한 도구를 다루는 것에 대해 논의합니다.

이동 중에 테스트를 위해 모의 개체와 스터브를 작성하려면 어떻게합니까?이동 중에 테스트를 위해 모의 개체와 스터브를 작성하려면 어떻게합니까?Mar 10, 2025 pm 05:38 PM

이 기사는 단위 테스트를 위해 이동 중에 모의와 스터브를 만드는 것을 보여줍니다. 인터페이스 사용을 강조하고 모의 구현의 예를 제공하며 모의 집중 유지 및 어설 션 라이브러리 사용과 같은 모범 사례에 대해 설명합니다. 기사

GO에서 제네릭에 대한 사용자 정의 유형 제약 조건을 어떻게 정의 할 수 있습니까?GO에서 제네릭에 대한 사용자 정의 유형 제약 조건을 어떻게 정의 할 수 있습니까?Mar 10, 2025 pm 03:20 PM

이 기사에서는 GO의 제네릭에 대한 사용자 정의 유형 제약 조건을 살펴 봅니다. 인터페이스가 일반 함수에 대한 최소 유형 ​​요구 사항을 정의하여 유형 안전 및 코드 재사성을 향상시키는 방법에 대해 자세히 설명합니다. 이 기사는 또한 한계와 모범 사례에 대해 설명합니다

Go의 반사 패키지의 목적을 설명하십시오. 언제 반사를 사용 하시겠습니까? 성능의 영향은 무엇입니까?Go의 반사 패키지의 목적을 설명하십시오. 언제 반사를 사용 하시겠습니까? 성능의 영향은 무엇입니까?Mar 25, 2025 am 11:17 AM

이 기사는 코드의 런타임 조작, 직렬화, 일반 프로그래밍에 유리한 런타임 조작에 사용되는 GO의 반사 패키지에 대해 설명합니다. 실행 속도가 느리고 메모리 사용이 높아짐, 신중한 사용 및 최고와 같은 성능 비용을 경고합니다.

GO에서 테이블 구동 테스트를 어떻게 사용합니까?GO에서 테이블 구동 테스트를 어떻게 사용합니까?Mar 21, 2025 pm 06:35 PM

이 기사는 테스트 케이스 테이블을 사용하여 여러 입력 및 결과로 기능을 테스트하는 방법 인 GO에서 테이블 중심 테스트를 사용하는 것에 대해 설명합니다. 가독성 향상, 중복 감소, 확장 성, 일관성 및 A와 같은 이점을 강조합니다.

추적 도구를 사용하여 GO 응용 프로그램의 실행 흐름을 이해하려면 어떻게해야합니까?추적 도구를 사용하여 GO 응용 프로그램의 실행 흐름을 이해하려면 어떻게해야합니까?Mar 10, 2025 pm 05:36 PM

이 기사는 추적 도구를 사용하여 GO 응용 프로그램 실행 흐름을 분석합니다. 수동 및 자동 계측 기술, Jaeger, Zipkin 및 OpenTelemetry와 같은 도구 비교 및 ​​효과적인 데이터 시각화를 강조합니다.

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 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

mPDF

mPDF

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

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.