PHpullh
학습 라이브러리/Go/HTTP 서버 심화

GO · 파일/IO

HTTP 서버 심화

net/http로 구조화된 HTTP 서버를 구현합니다. 라우팅, 미들웨어, 그레이스풀 셧다운을 다룹니다.

파일/IO고급http-servermuxgraceful-shutdowngo122

핵심 설명

net/http로 구조화된 HTTP 서버를 구현합니다. 라우팅, 미들웨어, 그레이스풀 셧다운을 다룹니다.

Go code

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"os/signal"
	"syscall"
	"time"
)

func jsonResponse(w http.ResponseWriter, status int, data any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	json.NewEncoder(w).Encode(data)
}

func main() {
	mux := http.NewServeMux()

	// Go 1.22+ 패턴 매칭
	mux.HandleFunc("GET /api/health", func(w http.ResponseWriter, r *http.Request) {
		jsonResponse(w, 200, map[string]string{"status": "ok"})
	})

	mux.HandleFunc("GET /api/users/{id}", func(w http.ResponseWriter, r *http.Request) {
		id := r.PathValue("id")
		jsonResponse(w, 200, map[string]string{"id": id})
	})

	srv := &http.Server{
		Addr:         ":8080",
		Handler:      mux,
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}

	// 그레이스풀 셧다운
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	go func() { fmt.Println("서버 시작 :8080"); srv.ListenAndServe() }()
	<-ctx.Done()
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	srv.Shutdown(shutdownCtx)
	fmt.Println("서버 종료")
}

학습 팁

Go 1.22부터 http.ServeMux"GET /api/users/{id}" 형식의 패턴 매칭을 지원합니다.

주의할 점

ReadTimeoutWriteTimeout을 설정하지 않으면 Slowloris 공격에 취약합니다. 반드시 타임아웃을 설정하세요.

자주 묻는 질문

HTTP 서버 심화란 무엇인가요?

net/http 로 구조화된 HTTP 서버를 구현합니다. 라우팅, 미들웨어, 그레이스풀 셧다운을 다룹니다.

HTTP 서버 심화 학습 시 주의할 점은 무엇인가요?

ReadTimeout 과 WriteTimeout 을 설정하지 않으면 Slowloris 공격에 취약합니다. 반드시 타임아웃을 설정하세요.