Go Lang/Study

Go로 CRUD REST API 만들기 (1)

DSeung 2023. 7. 5. 16:14

Go Lang으로 간단하게 CRUD  REST API 만들기  1편

1. 개요

간단한 CRUD API를 만들어봅시다, 제 경우 Go version은 1.20으로 개발했습니다.

HTTP 요청을 핸들링하기 위한 라이브러리로 gorilla/mux를 사용합니다.

사용 이유는 18.2k의 달하는 스타와 오랜 기간 안정성이 테스트되었기에 실무에서 쓰일만한 라이브러리라 판단하여 사용했습니다.

 

- Go 세팅이 되어있고 HTTP Method를 이해하고 있다는 가정하에 진행됩니다.

- 해당 포스트에서는 데이터베이스를 사용하지 않고 메모리를 통해서 데이터를 관리할 것입니다.

- 모든 코드는 main.go에서만 작업됩니다. 

- 1편에서는 GET을 다루고 2편에서 나머지를 다룹니다.

 

 

※ REST API : 인터넷을 통하여 컴퓨터 간의 정보를 안전하게 넘기기 위한 인터페이스 (AWS 기준)

※ CRUD :  만들 기능으로 Create, Read, Update, Delete의 약어의 연속

 

2. 코드

프로젝트 생성

폴더 생성 및 go mod int, 라이브러리 추가 

mkdir rest-api
cd rest-api
go mod init rest-api.com
go get github.com/gorilla/mux

이제 go.mod의 내용은 다음과 같습니다.

module rest-api.com

go 1.20

require github.com/gorilla/mux v1.8.0 // indirect

 

API Documentation

처음 코드를 실행하면 API에 대한 정보를 받을 수 있게 Documentation을 만듭니다.

package main

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/mux"
	"log"
	"net/http"
)

const port string = ":4000"

// urlDescription : url description 구조체
// `json:"url"`로 json 포멧일 시 출력되는 형태를 정의할 수 있음
// omitempty 를 추가하면 json 포멧에서 출력 안됨
type urlDescription struct {
	URL         string `json:"url"`
	Method      string `json:"method"`
	Description string `json:"description"`
	Payload     string `json:"payload,omitempty"`
}

func main() {
	// 라우터 생성
	router := mux.NewRouter()
	router.HandleFunc("/", documentation).Methods("GET")

	fmt.Printf("Listening on http://localhost%s\n", port)
	// 서버 실행
	log.Fatal(http.ListenAndServe(port, router))
}

// documentation : API 설명 출력
func documentation(rw http.ResponseWriter, r *http.Request) {
	// 앞으로 만들 API
	data := []urlDescription{
		{
			URL:         "/champions",
			Method:      "GET",
			Description: "Read champions",
		},
		{
			URL:         "/champions",
			Method:      "POST",
			Description: "Create champions",
		},
		{
			URL:         "/champions/{id}",
			Method:      "PATCH",
			Description: "Update champions",
		},
		{
			URL:         "/champions/{id}",
			Method:      "DELETE",
			Description: "Delete champions",
		},
	}
	// json 형태로 출력
	json.NewEncoder(rw).Encode(data)
}

위와 같이 입력 후 go run main.go로 실행하고 localhost:4000로 접속하면 Response로 아래와 같은 Json을 받을 수 있습니다.

아래와 같은 결과물은 크롬 브라우저에서 보실 수 있습니다, 타 브라우저에서는 문자열로 나올 수 있는데

이는 다음 코드에서 해결합니다.

 

Json Middleware

현재 코드로는 반환 타입의 Content-Type이 명시되지 않아 크롬을 제외한 브라우저에서는 단순 문자열로 인식합니다.

미들웨어를 추가하여 Htttp 응답에 자동으로 Content-Type을 추가하도록 해줍시다

// jsonContentTypeMiddleware : 반환 타입의 포멧을 Content-Type application/json 으로 정의
func jsonContentTypeMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		rw.Header().Add("Content-Type", "application/json")
		next.ServeHTTP(rw, r)
	})
}

func main도 수정하여 미들웨어를 연결합시다.

func main() {
	// 라우터 생성
	router := mux.NewRouter()
	router.Use(jsonContentTypeMiddleware)
	router.HandleFunc("/", documentation).Methods("GET")

	fmt.Printf("Listening on http://localhost%s\n", port)
	// 서버 실행
	log.Fatal(http.ListenAndServe(port, router))
}

 

GET (READ)

데이터를 메모리에 저장해 둘 것이니 관련 구조체랑 슬라이스를 선언합니다.
  slice(슬라이스) : Go에서는 배열은 크기를 명시해야하지만 slice는 크기를 유동적으로 사용이 가능

type champion struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

var champions []*champion

아직 CREATE가 없기에 확인을 위해 기본 값을 추가해 주고 GET에 대한 함수를 만들어줍시다.

func main() {
	// 기본 값 세팅
	maokai := &champion{
		1,
		"마오카이",
	}
	champions = append(champions, maokai)

	// 라우터 생성
	router := mux.NewRouter()
	router.Use(jsonContentTypeMiddleware)
    // GET 함수 연결
	router.HandleFunc("/", documentation).Methods("GET")
	router.HandleFunc("/champions", getChampions).Methods("GET")

	fmt.Printf("Listening on http://localhost%s\n", port)
	// 서버 실행
	log.Fatal(http.ListenAndServe(port, router))
}

func getChampions(rw http.ResponseWriter, r *http.Request) {
	json.NewEncoder(rw).Encode(champions)
}

이제 http://localhost:4000/champions로 접속하면 아래와 같이 반환됩니다.

 

의문점 문의 및 오타 피드백은 언제나 환영입니다.

 

다음 포스트입니다.

https://seung.tistory.com/entry/Go%EB%A1%9C-CRUD-REST-API-%EB%A7%8C%EB%93%A4%EA%B8%B0-2

 

Go로 CRUD REST API 만들기 (2)

Go Lang으로 간단하게 CRUD REST API 만들기 2편 1. 개요 이번 포스트로 Go로 Post, Patch, Delete 메서드에 핸들링할 수 있습니다. 1편에서 이어집니다, 1편을 보지 않으신 분들은 아래 링크로 가서 진행해 주

seung.tistory.com

 

반응형