Programming/Go
Go :: Go 로 REST API 작성해보기 / go rest api example
쿠마쿠마34
2023. 1. 11. 15:29
반응형
오늘은 Go 언어를 공부하면서 REST API 예제 코드를 작성해 보았습니다.
전체 코드는 아래 링크를 참고해주세요
https://github.com/kumakuma34/GoRestExample
GitHub - kumakuma34/GoRestExample: Go Rest API Example
Go Rest API Example. Contribute to kumakuma34/GoRestExample development by creating an account on GitHub.
github.com
- Router 라이브러리를 이용해서 서버를 띄웠습니다.
- 별도의 DB를 사용하지 않고 메모리를 이용해 테스트를 진행하였습니다.
📌 Go module 등록하기
→ 작업하고 있는 디렉토리 안에서 진행
go mod init example/GoRestExample
📌 데이터 모델 만들기
- Album이라는 데이터를 만들고 그 안에 들어갈 필드 값들을 정의한다.
- json: 뒤에 붙는 필드명과 일치 여부를 확인해 값을 json으로 Serialization할 때 사용한다.
- albums안에 데이터를 임시로 몇개 넣어두었다.
type album struct {
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Price float64 `json:"price"`
}
var albums = []album{
{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}
📌Go Dependency 추가하기
- gin~ 이 모듈을 가져오기 위해 아래 커맨드를 실행한다.
go run .
import (
"github.com/gin-gonic/gin"
"net/http"
)
📍GET Method
📌 함수 작성하기
- albums안에 있는 데이터를 모두 가져와서 json으로 전달하는 함수를 작성할 것이다.
- gin 라이브러리 안의 IndentedJSON 함수를 사용한다.
func getAlbums(c *gin.Context) {
c.IndentedJSON(http.StatusOK, albums)
}
📌서버를 띄우고 Method Path 설정하기
- Router를 사용해 Localhost 8080에 서버를 띄우고, 위에 만든 함수와 path를 설정해 “GET”메소드를 구현한다.
func main() {
router := gin.Default()
router.GET("/albums", getAlbums)
router.Run("localhost:8080")
}
- go run . 으로 서버를 실행하고, curl [<http://localhost:8080/albums>](<http://localhost:8080/albums>) 를 이용해 명령어를 실행하면 JSON 응답 값을 받을 수 있다.
[
{
"id": "1",
"title": "Blue Train",
"artist": "John Coltrane",
"price": 56.99
},
{
"id": "2",
"title": "Jeru",
"artist": "Gerry Mulligan",
"price": 17.99
},
{
"id": "3",
"title": "Sarah Vaughan and Clifford Brown",
"artist": "Sarah Vaughan",
"price": 39.99
}
]
📍POST Method 만들기
📌데이터를 추가하는 함수 작성
func postAlbums(c *gin.Context) {
var newAlbum album
if err := c.BindJSON(&newAlbum); err != nil {
return
}
albums = append(albums, newAlbum)
c.IndentedJSON(http.StatusCreated, newAlbum)
}
📌 함수와 Method를 연결하기
func main() {
router := gin.Default()
router.GET("/albums", getAlbums)
router.POST("/albums", postAlbums)
router.Run("localhost:8080")
}
📍특정 값을 가져오는 GET Method 만들기
📌 특정 값을 가져오는 함수 작성
- .Param을 통해 가져오고자 하는 데이터의 ID를 가져올 수 있다.
func getAlbumByID(c *gin.Context) {
id := c.Param("id")
for _, a := range albums {
if a.ID == id {
c.IndentedJSON(http.StatusOK, a)
return
}
}
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}
📌Method와 연결하기
func main() {
router := gin.Default()
router.GET("/albums", getAlbums)
router.GET("/albums/:id", getAlbumByID)
router.POST("/albums", postAlbums)
router.Run("localhost:8080")
}
✔️References
Tutorial: Developing a RESTful API with Go and Gin - The Go Programming Language
반응형