LoginSignup
3
2

More than 3 years have passed since last update.

[Go言語] httpライブラリのHandler,Handlefuncとかをざっくり整理

Posted at

はじめに

Go言語のhttpの標準ライブラリを利用すると、http.Handleとかhttp.Handlefuncとか似た名前が多い。
httpサーバを作るときによく使われるものについて、概念だけわかるようにかなりざっくり整理。

Handler

リクエスト受信時の処理を持つインターフェースと思っておけばいい
定義されているServeHTTPは結局のところリクエスト受信時処理

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}

http.Handle

URLと対応するHandlerをひもづける

URLに対してHandlerに定義されているリクエスト受信時処理が登録される

func Handle(pattern string, handler Handler)

http.Handlefunc

URLと対応するリクエスト受信時処理を直接ひもづける

使い方はhttp.Handleと同じ
Handleとの違いは、Handler(の処理)とひもづけるか、Handlerとして実体化させていない処理そのものとひもづけるかの違い

func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    DefaultServeMux.HandleFunc(pattern, handler)
}

実装時には

簡単なhttpサーバだと次の2ステップ

1.URLとURLリクエスト受信時の処理を登録する
 http.Handleとかhttp.Handlefuncとか

2.1.で登録した処理を指定のポートで待ち受け
 http.ListenAndServe

http.HandleFunc("/test/", testHandler)
log.Fatal(http.ListenAndServe(":8080", nil))

参考

GoでHTTPサーバー入門 [Handler][HandleFunc][ServeMux]
https://noumenon-th.net/programming/2019/09/12/handler/

Go 言語の http パッケージにある Handle とか
https://qiita.com/nirasan/items/2160be0a1d1c7ccb5e65

3
2
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
3
2