don't stop believing

핸들링 요청과 핸들링 함수 본문

Golang/Web App

핸들링 요청과 핸들링 함수

Tongchun 2019. 2. 2. 13:18

Golang으로 Web App 개발을 공부해 봅시다.

첫 번째 Webapp으로 hello world를 찍었다면 이번엔 핸들러 함수를 사용하는 것을 알아보겠습니다.

핸들러를 쉽게 설명하자면, Web Server가 어떤 요청을 받았을 때 그것을 처리하도록 하는 것입니다.


Go에서 핸들러는 인터페이스입니다. 인터페이스는 ServerHTTP로 명명된 메소드 입니다. 이 메소드에는 두 개의 매개변수를 같는데 첫 번째는 HTTPResponseWriter 인터페이스이고 두번째는 Request struct를 가리키는 포인터입니다.

ServeHTTP(w http.ResponseWriter, r *http.Request)

핸들링 요청에 대한 기본 코드는 아래와 같습니다.

package main

import (
	"fmt"
	"net/http"
)

type TongchunHandler struct{}

func (h *TongchunHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello Tongchun!")
}

func main() {
	handler := TongchunHandler{}
	server := http.Server{
		Addr: "127.0.0.1:8080",
		Handler: &handler,
	}
	server.ListenAndServe()
}

Go에는 Class가 없습니다. 그래서 TongchunHandler라는 struct를 만들고 ServerHTTP 메소드를 TongchunHandler에 상속시킵니다.

main 함수에서 TongchunHandler struct를 handler 변수에 대입하고 server의 Handler로 설정합니다.


빌드를 하고 실행해 보겠습니다. 아래 go 실행 명령의 위치는 gopath 입니다.

$ go install ./src/handler01/
$ ./bin/handler01 

위 처럼 빌드하고 실행했다면 브라우저에서 localhost:8080을 호출해 봅니다.

하지만 localhost:8080 뒤에 uri를 추가해도 동일한 화면이 보이게 됩니다.

이는 핸들러가 서버에 붙고 더 이상 멀티플렉서를 이용하지 않기 때문입니다. 어떤 요청이 들어와도 URL에 매칭되는 라우터가 없으므로 ServerHTTP 메소드가 요청된 모든 처리를 하게 됩니다. 그래서 Hello Tongchun! 외에 다른 응답을 하지 않게 됩니다.


이번에는 개별 URL을 처리하도록 두 개의 햄ㄷ르러를 만들어 보겠습니다.

위 코드을 아래와 같이 추가합니다.

package main

import (
	"fmt"
	"net/http"
)

type TongchunHandler struct{}

func (h *TongchunHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello Tongchun!")
}

type WelcomeHandler struct{}

func (h *WelcomeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Welcom Tongchun's world!")
}

func main() {
	helle := TongchunHandler{}
	welcom := WelcomeHandler{}

	server := http.Server{
		Addr: "127.0.0.1:8080",
	}

	http.Handle("/tongchun", &helle)
	http.Handle("/welcome", &welcom)

	server.ListenAndServe()
}

첫 번째 code에서 WelcomeHandler struct와 WelcomeHandler를 상속받은 serveHTTP 함수를 추가했습니다.

그리고 http.Server 설정안에 있던 Handler를 밖으로 빼 http.Handle()로 두 개를 만들었습니다.


다시 빌드를 하고 실행해 봅니다.

$ go install ./src/handler01/
$ ./bin/handler01 

실행되었다면 http.Handle()로 설정한 /tongchun 과 /welcome으로 접속해 봅니다.

지정한 URL로 접속하면 handler에 따라 잘 보이게 됩니다. 만약 그 외 경로로 접속했을 경우에는 404 page not found 메시지가 보이게 됩니다.


위 두 code는 ServerHTTP 핸들러를 사용했습니다. 이번에는 일반 함수를 ServerHTTP 핸들러 함수와 같이 사용해 보겠습니다.

package main

import (
	"fmt"
	"net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello Tongchun!")
}

func welcome(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Welcom Tongchun's world!")
}

func main() {

	server := http.Server{
		Addr: "127.0.0.1:8080",
	}

	http.HandleFunc("/tongchun", hello)
	http.HandleFunc("/welcome", welcome)

	server.ListenAndServe()
}

struct를 제거하고 Go에서 일반 함수를 만드는 것과 같이 작성합니다. 매개변수로는 ServeHTTP와 같이 HTTPResponseWriter 인터페이스와 Request struct를 가리키는 포인터를 넣습니다.

그리고 http.Handle 대신 http.HandleFunc를 사용했습니다.


빌드 후 실행하면 동일한 결과를 볼 수 있습니다.


'Golang > Web App' 카테고리의 다른 글

Header와 body 확인하기  (1) 2019.02.09
Handler와 Multiplexer 이해하기  (0) 2019.02.07
체이닝 함수  (0) 2019.02.06
첫 번째 웹 서버(Hello Tongchun!)  (0) 2019.01.31
Comments