GoLang — 소개 | 자동 다시 로드로 REST API 생성

GoLang — 소개 | 자동 재로드로 REST API 생성



Go는 Google에서 만든 고수준, 강력(변수 유형을 변경할 수 없음) 및 정적으로(모든 변수는 컴파일 시 선언되어야 함) 유형이 지정된 준수 프로그래밍 언어입니다.





주요 특징들


  • 단순성 — Go에는 매우 유용하고 필요한 기능만 있습니다.
  • 빠른 컴파일 — Go는 컴파일 시간이 거의 없습니다.
  • 가비지 컬렉션 — 가비지 컬렉션은 자동화된 메모리 관리 유형입니다.
  • 내장 동시성 — 기능이 서로 독립적으로 작동하는 기능.
  • 독립 실행형 바이너리로 컴파일됨

  • Gin — 웹 개발 프레임워크



    Gin allows you to create Go web apps and microservices. It includes a set of frequently used capabilities (e.g., routing, middleware support, rendering, etc.)



    이 기사에서는 CRUD(Create, Read, Update, Delete) 작업을 수행할 수 있는 Gin을 사용하여 간단한 GO 서버를 만들 것입니다. 또한 자동 재로드를 구현하여 일부 변경 후 서버를 계속해서 다시 시작할 필요가 없습니다.

    진을 사용하여 서버 만들기



    이 프로세스에는 단계가 포함됩니다.
  • GO 프로젝트를 생성합니다.
  • 프로젝트에서 Gin을 설치하고 가져옵니다.
  • 자동 다시 로드를 위한 AIR 구성을 추가합니다.
  • API 가져오기, 게시, 넣기 및 업데이트를 추가합니다.
  • 우편 배달부를 사용하여 응답을 검증하십시오.

  • 그래서, 우리는 첫 번째 단계부터 시작할 것입니다.

    GO 프로젝트 만들기



    먼저 프로젝트에서 GO를 초기화해야 합니다.

    go mod init gin-example-project
    


    우리 프로젝트의 루트 폴더에 go.mod 파일을 생성합니다.

    이제 main.go 파일을 만들어 코드 작성을 시작할 수 있습니다.

    모든 것이 작동하는지 테스트하려면 main.go 파일에 hello word program을 붙여넣고 실행하십시오.

    package main
    import "fmt"
    
    func main() {
        fmt.Println("Hello, World!")
    }
    


    이 코드를 실행하려면 간단히 명령-

    go run main.go
    
    _// expected output: Hello, World!_
    


    프로젝트에서 Gin 설치 및 가져오기



    Gin을 설치하려면 Go v1.13+가 필요합니다. 진을 설치하려면 다음을 실행하십시오.

    go get -u github.com/gin-gonic/gin
    


    설치 후 main.go 파일에서 gin을 가져올 수 있습니다.

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


    또한 상태를 보내려면 net/http가 필요합니다.

    import "net/http"
    


    자동 다시 로드를 위한 AIR 구성 추가



    프로젝트의 루트 폴더에 .air.conf 파일을 만들고 이 구성을 해당 파일에 추가합니다.

    import _ "github.com/joho/godotenv/autoload"
    root = "."
    tmp_dir = "tmp"
    
    [build]
    _# Just plain old shell command. You could use `make` as well._
    cmd = "go build -o ./tmp/main ."
    _# Binary file yields from `cmd`._
    bin = "tmp/main"
    _# Customize binary._
    full_bin = "APP_ENV=dev APP_USER=air ./tmp/main"
    _# Watch these filename extensions._
    include_ext = ["go", "tpl", "tmpl", "html"]
    _# Ignore these filename extensions or directories._
    exclude_dir = ["assets", "tmp", "vendor", "frontend/node_modules"]
    _# Watch these directories if you specified._
    include_dir = []
    _# Exclude files._
    exclude_file = []
    _# It's not necessary to trigger build each time file changes if it's too frequent._
    delay = 1000 _# ms_
    _# Stop to run old binary when build errors occur._
    stop_on_error = true
    _# This log file places in your tmp\_dir._
    log = "air_errors.log"
    
    [log]
    _# Show log time_
    time = false
    
    [color]
    _# Customize each part's color. If no color found, use the raw app log._
    main = "magenta"
    watcher = "cyan"
    build = "yellow"
    runner = "green"
    
    [misc]
    _# Delete tmp directory on exit_
    clean_on_exit = true
    


    이제 AIR를 사용하여 프로젝트를 실행해야 합니다. 그래서 당신은 명령해야합니다-

    air run main.go
    


    GET, POST, PUT 및 UPDATE API 추가



    이를 위해 몇 가지 샘플 데이터를 추가했습니다. 여기에서 복사할 수 있습니다https://github.com/gyanendraknojiya/GO-Gin-REST-API#get-all-users

    main.go 파일에 main 함수를 만들고 서버를 포트 8080(포트는 아무거나 가능)으로 실행합니다.

    func main(){
        router := gin.Default()
        router.Run("localhost:8080")
    }
    


    이제 서버가 실행되는 것을 볼 수 있습니다. 사용자 json을 생성해야 합니다.

    type user struct {
        ID string `json:"id"`
        Name string `json:"name"`
        UserName string `json:"userName"`
        Email string `json:"email"`
        Phone string `json:"phone"`
        Website string `json:"website"`
    }
    
    var users = []user{
        {
            ID: "1",
            Name: "Leanne Graham",
            UserName: "Bret",
            Email: "[email protected]",
            Phone: "1-770-736-8031 x56442",
            Website: "hildegard.org",
        },
        {
            ID: "2",
            Name: "Ervin Howell",
            UserName: "Antonette",
            Email: "[email protected]",
            Phone: "010-692-6593 x09125",
            Website: "anastasia.net",
        },
    }
    


    주요 기능에 모든 API 추가-

    func main() {
        router := gin.Default()
    
        router.GET("/", getAllUsers)
        router.GET("/user/:id", getUserById)
        router.POST("/addUser", addUser)
        router.PUT("/updateUser", updateUser)
        router.DELETE("/deleteUser", deleteUser)
    
        router.Run("localhost:8080")
    }
    


    getAllUsers

    func getAllUsers(c *gin.Context) {
        c.IndentedJSON(http.StatusOK, users)
    }
    


    getUserById

    func getUserById(c *gin.Context) {
        ID := c.Param("id")
        for _, i := range users {
            if i.ID == ID {
                c.IndentedJSON(http.StatusOK, i)
                return
            }
        }
        c.IndentedJSON(http.StatusNotFound, gin.H{"message": "user not found!"})
    }
    


    사용자 추가

    func addUser(c *gin.Context) {
        var newUser user
    
        if err := c.BindJSON(&newUser); err != nil {
            fmt.Println(err)
            return
        }
    
        users = append(users, newUser)
        c.IndentedJSON(http.StatusOK, users)
    }
    


    업데이트 사용자

    func updateUser(c *gin.Context) {
        var updateUser user
    
        if err := c.BindJSON(&updateUser); err != nil {
            fmt.Println(err)
            return
        }
        if updateUser.ID == "" {
            c.IndentedJSON(400, gin.H{"message": "id is missing!"})
            return
        }
    
        for i, user := range users {
            if user.ID == updateUser.ID {
    
                if updateUser.Name != "" {
                    user.Name = updateUser.Name
                }
                if updateUser.Email != "" {
                    user.Email = updateUser.Email
                }
                if updateUser.Phone != "" {
                    user.Phone = updateUser.Phone
                }
                if updateUser.Website != "" {
                    user.Website = updateUser.Website
                }
                users[i] = user
                c.IndentedJSON(http.StatusOK, users)
                return
            }
        }
        c.IndentedJSON(400, gin.H{"message": "id is not found!"})
    }
    


    사용자 삭제

    func RemoveIndex(s []user, index int) []user {
        return append(s[:index], s[index+1:]...)
    }
    
    func deleteUser(c *gin.Context) {
        var deleteUser user
    
        if err := c.BindJSON(&deleteUser); err != nil {
            fmt.Println(err)
            return
        }
        if deleteUser.ID == "" {
            c.IndentedJSON(400, gin.H{"message": "id is missing!"})
            return
        }
    
        for i, user := range users {
            if user.ID == deleteUser.ID {
                users = RemoveIndex(users, i)
                c.IndentedJSON(http.StatusOK, users)
                return
            }
        }
        c.IndentedJSON(400, gin.H{"message": "id is not found!"})
    }
    


    그게 다야. 이제 이러한 API를 사용하여 서버에서 데이터를 가져오고, 추가하고, 업데이트하고, 제거할 수 있습니다.

    소스 코드: https://github.com/gyanendraknojiya/GO-Gin-REST-API

    여기서 커피 사주세요 https://www.buymeacoffee.com/gyanknojiya

    문의사항이 있으시면 언제든지 저에게 연락주세요here

    2021년 12월 2일 https://codingcafe.co.in에 원래 게시되었습니다.

    좋은 웹페이지 즐겨찾기