[go] net/http 패키지를 사용한 URL 라우팅 처리

Go 언어에서 웹 애플리케이션을 개발할 때 net/http 패키지는 핵심적인 역할을 수행합니다. 이 패키지를 사용하여 URL 라우팅 처리를 구현할 수 있습니다. URL 라우팅은 요청된 URL에 따라 적절한 핸들러 함수를 호출하는 과정을 말합니다.

URL 라우팅 기본 설정

먼저, URL 라우팅을 구현하기 위해 기본적인 설정을 해야 합니다. 아래는 / 경로에 대한 핸들러 함수를 설정하는 예제 코드입니다.

package main

import (
	"fmt"
	"net/http"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Welcome to the home page")
}

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

위의 코드에서 http.HandleFunc 함수를 사용하여 / 경로에 대한 요청이 들어왔을 때 homeHandler 함수를 호출하도록 설정했습니다. 이제 / 경로로의 요청이 들어오면 homeHandler 함수가 실행되어 “Welcome to the home page”를 출력합니다.

다중 URL 라우팅 처리

다음은 여러 개의 URL을 다루는 방법을 보여주는 예제 코드입니다.

func aboutHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "This is the about page")
}

func contactHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Contact us at: example@email.com")
}

func main() {
	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/about", aboutHandler)
	http.HandleFunc("/contact", contactHandler)
	http.ListenAndServe(":8080", nil)
}

위의 코드에서는 /about/contact 경로에 대한 핸들러 함수를 설정하였습니다. 이제 각 URL에 해당하는 핸들러 함수가 요청에 따라 실행됩니다.

URL 매개변수 활용

가끔은 동적인 URL을 다뤄야 할 때가 있습니다. 이때 URL 매개변수를 활용하여 다양한 동적 URL을 처리할 수 있습니다.

func articleHandler(w http.ResponseWriter, r *http.Request) {
	articleID := r.URL.Query().Get("id")
	fmt.Fprintf(w, "You requested article with ID: %s", articleID)
}

func main() {
	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/article", articleHandler)
	http.ListenAndServe(":8080", nil)
}

위의 코드에서 /article 경로에 대한 요청 시 articleID 변수를 추출하여 해당하는 게시글을 표시해 줄 수 있습니다.

이처럼 Go의 net/http 패키지를 사용하여 간단한 URL 라우팅 처리를 쉽게 구현할 수 있습니다. 많은 웹 프레임워크와 유사한 패턴을 따르며, 웹 애플리케이션을 개발할 때 유용하게 사용될 수 있습니다.

참고 문헌: Go net/http 패키지 문서