프로젝트 실행

go run main.go

웹 브라우저를 열고 http://localhost:8080

으로 이동합니다.

테스트

모든 제품 받기

\\\"제품 가져오기\\\" 버튼을 클릭하세요. API는 모든 제품 데이터를 반환합니다.

\\\"Create

ID로 제품 가져오기

\\\"제품 가져오기\\\" 버튼을 클릭하고 제품 ID에 \\\"1\\\"을 입력합니다. API는 제품 데이터를 반환합니다.

\\\"Create

제품 생성

\\\"Create Product\\\" 버튼을 클릭하고 제품 이름에 \\\"test-create\\\", 가격에 \\\"100\\\"을 입력합니다. API는 새로 생성된 제품을 반환합니다.

\\\"Create

제품 업데이트

\\\"제품 업데이트\\\" 버튼을 클릭하고 제품 ID에 \\\"101\\\", 이름에 \\\"test-update\\\", 가격에 \\\"200\\\"을 입력합니다. API는 업데이트된 제품을 반환합니다.

\\\"Create

제품 삭제

\\\"제품 삭제\\\" 버튼을 클릭하고 제품 ID에 \\\"101\\\"을 입력하세요. API는 아무것도 반환하지 않습니다. 이는 API에서 아무것도 반환하지 않으므로 허용됩니다.

\\\"Create

결론

이 글에서는 CRUD API를 생성하기 위해 Gin 프레임워크를 생성하고 설정하는 방법을 배웠습니다. GORM을 ORM으로 활용하여 데이터베이스에서 CRUD 작업을 수행합니다. JavaScript를 사용하여 API를 테스트해 보세요. 이 기사를 즐겨보시기 바랍니다.

소스 코드: https://github.com/StackPuz/Example-CRUD-Go

CRUD 웹 앱 만들기: https://stackpuz.com

","image":"http://www.luping.net/uploads/20240815/172373328366be1523a3829.jpg","datePublished":"2024-08-15T22:48:03+08:00","dateModified":"2024-08-15T22:48:03+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > Go로 CRUD API 만들기

Go로 CRUD API 만들기

2024-08-15에 게시됨
검색:822

Create a CRUD API with Go

CRUD 작업(생성, 읽기, 업데이트, 삭제)은 데이터베이스 작업 시 모든 웹 애플리케이션의 기본 기능입니다. 이 예에서는 Go를 사용하여 CRUD API를 생성하고 MySQL을 데이터베이스로 사용하는 방법을 보여줍니다.

전제 조건

  • 1.21로 이동
  • MySQL

프로젝트 설정

Go 프로젝트 종속성을 설정합니다.

go mod init app
go get github.com/gin-gonic/gin
go get gorm.io/gorm
go get gorm.io/driver/mysql
go get github.com/joho/godotenv

"example"이라는 테스트 데이터베이스를 만들고 table.sql 파일을 실행하여 테이블과 데이터를 가져옵니다.

프로젝트 구조

├─ .env
├─ main.go
├─ config
│  └─ db.go
├─ controllers
│  └─ product_controller.go
├─ models
│  └─ product.go
├─ public
│  └─ index.html
└─ router
   └─ router.go

프로젝트 파일

.env

이 파일에는 데이터베이스 연결 정보가 포함되어 있습니다.

DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=example
DB_USER=root
DB_PASSWORD=

db.go

이 파일은 GORM을 사용하여 데이터베이스 연결을 설정합니다. 나중에 애플리케이션에서 사용할 데이터베이스 연결 인스턴스를 보유하기 위해 전역 변수 DB를 선언합니다.

package config

import (
    "fmt"
    "os"

    "github.com/joho/godotenv"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/schema"
)

var DB *gorm.DB

func SetupDatabase() {
    godotenv.Load()
    connection := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_HOST"), os.Getenv("DB_PORT"), os.Getenv("DB_DATABASE"))
    db, _ := gorm.Open(mysql.Open(connection), &gorm.Config{NamingStrategy: schema.NamingStrategy{SingularTable: true}})
    DB = db
}

router.go

이 파일은 Gin 웹 애플리케이션에 대한 라우팅을 설정합니다. 라우터를 초기화하고, 루트 URL에서 정적 index.html 파일을 제공하고, CRUD 작업을 위한 API 경로를 정의합니다.

package router

import (
    "app/controllers"

    "github.com/gin-gonic/gin"
)

func SetupRouter() {
    productController := controllers.ProductController{}
    router := gin.Default()
    router.StaticFile("/", "./public/index.html")
    router.Group("/api").
        GET("/products", productController.Index).
        POST("/products", productController.Create).
        GET("/products/:id", productController.Get).
        PUT("/products/:id", productController.Update).
        DELETE("/products/:id", productController.Delete)
    router.Run()
}

product.go

이 파일은 애플리케이션의 제품 모델을 정의합니다. 이 모델은 제품과 관련된 데이터베이스 작업에 사용됩니다.

package models

type Product struct {
    Id int `gorm:"primaryKey;autoIncrement"`
    Name string
    Price float64
}

product_controller.go

이 파일은 들어오는 요청을 처리하고 CRUD 작업을 수행하는 데 필요한 모든 기능을 정의합니다.

package controllers

import (
    "app/config"
    "app/models"
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
)

type ProductController struct {
}

func (con *ProductController) Index(c *gin.Context) {
    var products []models.Product
    config.DB.Find(&products)
    c.JSON(http.StatusOK, products)
}

func (con *ProductController) Get(c *gin.Context) {
    var product models.Product
    config.DB.First(&product, c.Params.ByName("id"))
    c.JSON(http.StatusOK, product)
}

func (con *ProductController) Create(c *gin.Context) {
    var product models.Product
    c.BindJSON(&product)
    if err := config.DB.Create(&product).Error; err != nil {
        c.AbortWithError(http.StatusBadRequest, err)
        return
    }
    c.JSON(http.StatusOK, product)
}

func (con *ProductController) Update(c *gin.Context) {
    var product models.Product
    c.BindJSON(&product)
    product.Id, _ = strconv.Atoi(c.Params.ByName("id"))
    if err := config.DB.Updates(&product).Error; err != nil {
        c.AbortWithError(http.StatusBadRequest, err)
        return
    }
    c.JSON(http.StatusOK, product)
}

func (con *ProductController) Delete(c *gin.Context) {
    var product models.Product
    if err := config.DB.Delete(&product, c.Params.ByName("id")).Error; err != nil {
        c.AbortWithError(http.StatusBadRequest, err)
        return
    }
    c.Status(http.StatusOK)
}

c.BindJSON()은 요청 본문의 JSON 페이로드를 Go 구조체로 구문 분석합니다.

config.DB 원하는 데이터베이스 작업을 수행하는 데 사용되는 GORM 인스턴스입니다.

c.JSON()은 작업 결과와 적절한 HTTP 상태 코드가 포함된 JSON 응답을 보냅니다.

main.go

이 파일은 애플리케이션의 주요 진입점입니다. Gin 웹 애플리케이션을 생성하고 설정합니다.

package main

import (
    "app/config"
    "app/router"
)

func main() {
    config.SetupDatabase()
    router.SetupRouter()
}

index.html

이 파일은 API 테스트를 위한 기본 사용자 인터페이스를 만드는 데 사용됩니다.


    


    

Example CRUD

릴리스 선언문 이 글은 https://dev.to/stackpuz/create-a-crud-api-with-go-964?1에서 복제됩니다.1 침해 내용이 있는 경우, [email protected]으로 연락하여 삭제하시기 바랍니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3