Go 언어 18강 - RESTful JSON API 설계

 

📘 Go 언어 18강 - RESTful JSON API 설계

이번 시간엔 Go로 RESTful JSON API를 설계하고 구현하는 방법을 배웁니다.
API는 외부 프로그램과 통신할 수 있는 인터페이스로, JSON을 주고받는 것이 일반적입니다.

1️⃣ 기본 API 구조

핵심은 URL 경로, 메서드(GET/POST 등), JSON 입출력입니다.

type Message struct {
    Content string `json:"content"`
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodGet {
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        return
    }

    msg := Message{"안녕하세요!"}
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(msg)
}

2️⃣ POST 요청 받기

func echoHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        return
    }

    var msg Message
    err := json.NewDecoder(r.Body).Decode(&msg)
    if err != nil {
        http.Error(w, "Bad request", http.StatusBadRequest)
        return
    }

    json.NewEncoder(w).Encode(msg) // 그대로 응답
}

3️⃣ 전체 라우팅 설정

func main() {
    http.HandleFunc("/api/hello", helloHandler)
    http.HandleFunc("/api/echo", echoHandler)
    http.ListenAndServe(":8080", nil)
}

💡 예제: curl로 테스트

# GET 요청
curl http://localhost:8080/api/hello

# POST 요청
curl -X POST -H "Content-Type: application/json" \
  -d '{"content":"반가워요"}' \
  http://localhost:8080/api/echo

🧠 요약

  • GET 요청 → 경로에 따른 JSON 응답
  • POST 요청 → Body에서 JSON 수신
  • json.NewEncoder/Decoder로 처리

한 줄 요약: "Go의 net/http 만으로도 REST API 서버를 만들 수 있다!"