[go] Go 언어를 사용한 RESTful API의 HTTP 메서드 처리

Go 언어는 간편한 문법과 고성능을 지원하여 RESTful API 개발에 매우 적합한 언어입니다. 이 글에서는 Go를 사용하여 RESTful API의 HTTP 메서드를 처리하는 방법에 대해 알아보겠습니다.

목차

  1. GET 메서드 처리
  2. POST 메서드 처리
  3. PUT 메서드 처리
  4. DELETE 메서드 처리

GET 메서드 처리

GET 메서드는 서버로부터 데이터를 가져오는 용도로 사용됩니다. Go에서는 net/http 패키지를 사용하여 GET 요청을 처리할 수 있습니다. 다음은 GET 메서드를 처리하는 예제 코드입니다.

package main

import (
    "net/http"
    "encoding/json"
)

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

func getUser(w http.ResponseWriter, r *http.Request) {
    // 사용자 정보를 가져오는 로직
    user := User{ID: 1, Name: "John Doe"}

    // JSON 형식으로 응답
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(user)
}

func main() {
    http.HandleFunc("/user", getUser)
    http.ListenAndServe(":8080", nil)
}

POST 메서드 처리

POST 메서드는 서버에 데이터를 생성하기 위해 사용됩니다. Go에서는 POST 요청을 처리하기 위해 http.Request를 사용하여 데이터를 읽어올 수 있습니다. 다음은 POST 메서드를 처리하는 예제 코드입니다.

func createUser(w http.ResponseWriter, r *http.Request) {
    // 요청 바디의 JSON 데이터 파싱
    var user User
    json.NewDecoder(r.Body).Decode(&user)

    // 사용자 생성 로직
    // ...

    // 응답
    w.WriteHeader(http.StatusCreated)
    w.Write([]byte("User created successfully"))
}

PUT 메서드 처리

PUT 메서드는 서버의 데이터를 업데이트하기 위해 사용됩니다. Go에서는 PUT 요청을 처리하기 위해 http.Request를 사용하여 데이터를 읽어오고 업데이트 로직을 구현할 수 있습니다. 다음은 PUT 메서드를 처리하는 예제 코드입니다.

func updateUser(w http.ResponseWriter, r *http.Request) {
    // 요청 바디의 JSON 데이터 파싱
    var user User
    json.NewDecoder(r.Body).Decode(&user)

    // 사용자 업데이트 로직
    // ...

    // 응답
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("User updated successfully"))
}

DELETE 메서드 처리

DELETE 메서드는 서버의 데이터를 삭제하기 위해 사용됩니다. Go에서는 DELETE 요청을 처리하기 위해 http.Request를 사용하여 데이터를 읽어오고 삭제 로직을 구현할 수 있습니다. 다음은 DELETE 메서드를 처리하는 예제 코드입니다.

func deleteUser(w http.ResponseWriter, r *http.Request) {
    // 요청 파라미터에서 삭제할 사용자 ID 가져오기
    id := r.URL.Query().Get("id")

    // 사용자 삭제 로직
    // ...

    // 응답
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("User deleted successfully"))
}

참고 자료