首页 > 代码库 > 构建HTTP中间件

构建HTTP中间件

第一种方式,使用类型形式构建HTTP中间件,结构myHandler有个属性是http.Handler类型,这个类型有个ServeHTTP方法

package main

import (
	"fmt"
	"net/http"
)


type myHandler struct {
	Addrhost string
	Headler  http.Handler
}

func (this *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	this.Headler.ServeHTTP(w, r)
}

func HandlerFunc(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.Host)
	w.Write([]byte("你好世界"))
}

func main() {
	my := &myHandler{
		Headler:  http.HandlerFunc(HandlerFunc),
		Addrhost: ":8080",
	}
	http.ListenAndServe(":8080", my)
}



第二种方式,函数方式
package main

import (
	"fmt"
	"net/http"
)

func gethandler(addhost string, headler http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		fmt.Println(r.Host)
		headler.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}

func myhandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("你好世界"))
}

func main() {
	hd := gethandler(":8080", http.HandlerFunc(myhandler))
	http.ListenAndServe(":8080", hd)

}



构建HTTP中间件