0
0

More than 5 years have passed since last update.

GO#5.1 マルチプレクサ続き

Last updated at Posted at 2019-02-11

http.Handleについて

http.HandleはDefaultServeMuxに、ハンドラを付加してくれるメソッドです。

http.Handle == http.ServeMux.DefaultServeMux.Handleと同じと捉えていいぽい。

こうして自分で作ったハンドラ関数、ハンドラをDefaultServeMuxにぶちこんでる。(表現汚いですよね、わかってま
す)

ハンドラの定義は(誤魔化しなし)

ServeHTTPという名前がついてる。
第一引数がhttp.ResponseWriterで第2引数が*http.Requestって形になってるもの。

でも実際書かれてるものは

hello.go
...

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

みたいな形がおおいいとおもいます。

え、ServeHTTPって名前の関数じゃないじゃん!!って思いますよね。

ここからハンドラ関数がハンドラになるまでを説明したいと思います。

GO言語には、HandlerFuncという名前の関数があります。
このHandlerFunc、helloという関数をメソッドhelloを持つハンドラに変換してくれます。
(FuncToHandlerって名前の関数だったら分かりやすかったのにね笑)

func hello(w http.ResponseWriter, r *http.Request){
  fmt.Fprintf(w, "hello")
}
func main() {
  server := http.Server{
   Addr: "127.0.0.1:8080"
  }
 http.HandleFunc("/hello", hello)
 server.ListenAndServe()
}

出てきましたね、HandleFunc

HandleFunc

ここでhttp.HandleFuncがやってくれてることは、
関数helloをハンドラに変換して、そのハンドラをDefaultServeMuxに登録してくれてます。
そして、そのハンドラをURLの"/hello"と紐付けてくれてます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0