0
0

はじめに

Goの標準パッケージを使ったプログラミングに慣れるために、net/httpだけでミドルウェアを書いてみました。

next.ServeHTTP(w, r)の前に書くか、後に書くかで、いつ処理されるかが決まるようです。

package main

import (
	"net/http"
)

func middleware1(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("before middleware\n"))
		next.ServeHTTP(w, r)
	})
}

func middleware2(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		next.ServeHTTP(w, r)
		w.Write([]byte("after middleware\n"))
	})
}

func main() {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello World\n"))
	})

	http.Handle("/", middleware1(middleware2(handler)))

	http.ListenAndServe(":8080", nil)
}

動かしてみる

curl http://localhost:8080

before middleware
Hello World
after middleware
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