웹서버를 시작하는 첫걸음으로 실제 동작하는 간단한 서버를 만들어 보기로 하자.
net/http
패키지를 사용하면 요청된 경로 또는 방식에 따라 서로 다른 Handler로 연결시키는 방법은 두가지가 있다.
1. HandleFunc을 사용하는 방법
package main
import (
"net/http"
"fmt"
"log"
)
func simpleHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World!")
}
func main() {
port := 8080
http.HandleFunc("/", simpleHandler)
log.Printf("Server starting on port %v\n", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v",port), nil))
}
ListenAndServe
ListenAndServe
함수는 TCP 통신 주소인 addr변수로 들어오는 통신 요청들을 받아서
Serve 함수를 통해 handler 함수를 실행 시킨다.
허용된 통신 요청들은 TCP keep-alives(TCP를 계속 연결시켜둔다는 의미)를 활성화 시키도록 설정된다.
handler 파라미터는 nil이 할당되면 DefaultServeMux
를 사용한다.
ListenAndServe는 항상 non-nil 에러를 리턴한다.
func ListenAndServe(addr string, handler Handler) error
http.ListenAndServe(”:8080”, nil)
HandleFunc
HandleFunc
는 http package의 package function으로서 DefaultServeMux에 pattern 파라미터와 handler 함수를 등록하는 메서드이다.
이 함수를 호출하면 실제로는 간접적으로 http.DefaultServeMux.HandleFunc를 호출한다.
pattern들이 어떻게 매칭되는지는 ServeMux의 문서를 살펴보면 된다.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
위의 코드는 simpleHandler라는 함수를 >handler func(ResponseWriter, *Request)
라는 익명함수 타입에 맞게 만들어 파라마터로 전달하는 방법이다
HandlerFunc
HandlerFunc
타입은 보통의 HTTP handlers 같은 함수들의 사용을 허용하는 어댑터이다.
만약 어떤 함수가 적절한 시그니처를 가진 함수라면 HandlerFunc(f)는 f를 호출하는 Handler일 것이다.
type HandlerFunc func(ResponseWriter, *Request)
FileServer
// FileServer returns a handler that serves HTTP requests // with the contents of the file system rooted at root. // // To use the operating system’s file system implementation, // use http.Dir: // // http.Handle(“/”, http.FileServer(http.Dir(“/tmp”))) // // As a special case, the returned file server redirects any request // ending in “/index.html” to the same path, without the final // “index.html”.
func FileServer(root FileSystem) Handler
NotFoundHandler
// NotFoundHandler returns a simple request handler // that replies to each request with a ``404 page not found” reply.
func NotFoundHandler() Handler { return HandlerFunc(NotFound) }