http/net 을 통한 기본적인 핸들러 생성
package main
import (
"fmt"
"net/http"
)
type fooHandler struct{}
func (f *fooHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello Foo!")
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello World")
})
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello World bar")
})
http.Handle("/foo", &fooHandler{})
http.ListenAndServe(":8080", nil)
}
설명 :
// 초기화된 fooHandler
// fooHandler 인스턴스 생성
type fooHandler struct{}
// 이미 초기화된 fooHanlder를 호출하여 사용
// ServeHTTP 인터페이스 구현(fooHandler)
func (f *fooHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello Foo!")
}
참고 : http://pyrasis.com/book/GoForTheReallyImpatient/Unit32
인터페이스 참고