26
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Go言語] httpハンドラの共通部分を取り出していい感じにする

Posted at

ハンドラをラップするようなハンドラを作る関数つくればいい。

package main

import (
    "fmt"
    "log"
    "net/http"
)

func baseHandlerFunc(handler func(w http.ResponseWriter, r *http.Request)) http.Handler {
    return baseHandler(http.HandlerFunc(handler))
}

func baseHandler(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // common
        log.Println(r.URL, r.Method)
        handler.ServeHTTP(w, r)
    })
}

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

func main() {
    http.Handle("/", baseHandlerFunc(index))
    http.ListenAndServe(":8080", nil)
}
26
30
1

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
26
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?