시작하며

Go는 표준 라이브러리 net/http만으로 HTTP 웹서버를 구축할 수 있다. 별도 프레임워크 없이도 핸들러 등록, 쿼리 파라미터 처리, 파일 서버 구성이 가능하다. 이 글에서는 Go 웹서버의 기본 구성 요소를 코드 예시와 함께 정리한다.

HTTP Web Server 기초

1. 핸들러 등록

func IndexPathHandler(w http.ResponseWriter, r *http.Request) {
	...
}
 
http.HandleFunc("/", IndexPathHandler)

2. 웹서버 시작

ListenAndServe 함수 시그니처는 다음과 같다.

func ListenAndServe(addr string, handler Handler) error
import (
	"fmt"
	"net/http"
)
 
func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "Hello World")
	})
	
	http.ListenAndServe(":3000" , nil)
}

HTTP WebServer 추가 기능

HTTP 쿼리 파라미터 사용하기

import (
	"fmt"
	"net/http"
	"strconv"
)
 
func barHandler(w http.ResponseWriter, r *http.Request) {
	values := r.URL.Query() // 쿼리 인수 가져오기
	name := values.Get("name") // 특정 키값이 있는지 확인
	if name == "" {
		name = "World"
	}
	id, _ := strconv.Atoi(values.Get("id")) // id값을 가져와서 int 타입 변환
	fmt.Fprintf(w, "Hello %s! id:%d", name, id)
}
 
func main() {
	http.HandleFunc("/bar", barHandler) // "/bar" 핸들러 등록
	http.ListenAndServe(":3000", nil)
}

ServeMux(Router) 인스턴스 사용하기

mux는 router와 같은 개념이다.

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello World")
	})
 
	mux.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "Hello World")
	})
 
	http.ListenAndServe(":3000", mux)
}
http://localhost:3000/bar?id=5&name=aaa

파일 서버

func main() {
	// 기본 경로에서 이미지가 나오도록 만들기
	http.Handle("/", http.FileServer(http.Dir("static")))
	
	// 특정 경로에서 이미지가 나오도록 만들기
	http.Handle("/static/", 
		http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
 
	http.ListenAndServe(":3000", nil)
}
http://localhost:3000/europe.jpeg
http://localhost:3000/static/europe.jpeg

정리하며

Go의 net/http 패키지는 외부 프레임워크 없이도 실용적인 웹서버를 구성할 수 있게 해준다. http.HandleFunc로 핸들러를 등록하고, http.NewServeMux로 라우터를 명시적으로 관리할 수 있다. 파일 서버는 http.FileServerhttp.StripPrefix를 조합해 경로 기반으로 정적 파일을 제공한다. 웹서버 테스트 코드, JSON 데이터 전송, HTTPS 설정은 심화 주제로 별도로 다룬다.