티스토리 뷰

반응형

Go로 간단한 REST API 서버 만들기 – net/http 기반 실습

이번 글에서는 Go의 표준 라이브러리인 net/http를 사용하여 가장 기본적인 RESTful API 서버를 만드는 방법을 알아봅니다.
Admin Dashboard의 백엔드로 사용할 API 서버의 기초 뼈대를 구성하는 중요한 단계입니다.


✅ 1. HTTP 서버 시작하기

📄 main.go 기본 코드

package main

import (
  "fmt"
  "net/http"
)

func main() {
  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Welcome to Go Admin API")
  })

  fmt.Println("🚀 Server started at :8080")
  http.ListenAndServe(":8080", nil)
}

✅ 실행

go run main.go

✅ 2. 기본적인 CRUD 라우팅 만들기

func main() {
  http.HandleFunc("/users", getUsers)
  http.HandleFunc("/users/create", createUser)
  http.HandleFunc("/users/delete", deleteUser)

  http.ListenAndServe(":8080", nil)
}

각 요청 메서드는 http.Request.Method를 통해 구분합니다.

func getUsers(w http.ResponseWriter, r *http.Request) {
  if r.Method == "GET" {
    w.Header().Set("Content-Type", "application/json")
    w.Write([]byte(`[{"id":1,"name":"admin"}]`))
  }
}

✅ 3. JSON 요청/응답 처리

반응형

📥 요청 Body 파싱 (POST)

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

func createUser(w http.ResponseWriter, r *http.Request) {
  if r.Method != "POST" {
    http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
    return
  }

  var u User
  json.NewDecoder(r.Body).Decode(&u)

  fmt.Fprintf(w, "User Created: %s", u.Name)
}

✅ 4. 공통 미들웨어 작성

간단한 로깅 미들웨어를 예로 들어보겠습니다.

func withLogging(h http.HandlerFunc) http.HandlerFunc {
  return func(w http.ResponseWriter, r *http.Request) {
    log.Printf("[%s] %s", r.Method, r.URL.Path)
    h(w, r)
  }
}

적용 방법:

http.HandleFunc("/users", withLogging(getUsers))

✅ 5. 상태 코드와 헤더 설정

w.WriteHeader(http.StatusCreated)
w.Header().Set("Content-Type", "application/json")

응답 상태 코드와 헤더는 항상 명시적으로 설정하는 습관을 들이는 것이 좋습니다.


✅ 6. 개발 편의를 위한 핫 리로드 도구

  • air: 실시간 코드 변경 반영
go install github.com/cosmtrek/air@latest

✅ 마무리

Go의 net/http만으로도 꽤 강력한 API 서버를 구축할 수 있습니다.
하지만 라우팅이 많아질수록 복잡해지므로, 다음 글에서는 gorilla/mux 또는 chi를 활용한 RESTful 라우팅 구조 개선을 다룰 예정입니다.


 

GoRESTAPI, GoHTTP서버, nethttp사용법, Go백엔드예제, JSON응답처리, Go핸들러, Go미들웨어, Go서버구축, AdminDashboardAPI, Golang실습

※ 이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함
반응형