构建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)

}



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。