源码:
package main
import (
"fmt"
"net/http"
. "github.com/soekchl/myUtils"
)
func main() {
finalHandler := http.HandlerFunc(final) // 设定最后访问
http.Handle("/", middleware(finalHandler)) // 设置中间件
if err := http.ListenAndServe(":8088", nil); err != nil {
Error(err)
return
}
}
func final(w http.ResponseWriter, r *http.Request) {
Info("final handler")
fmt.Fprintln(w, "final")
}
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Info("middleware handler")
id := r.FormValue("id") // 判断是否有 id 和 passwd 变量
passwd := r.FormValue("passwd")
if id == "" { // 没有先从cookie 获取
c, err := r.Cookie("id")
if err == nil {
id = c.Value
}
}
if passwd == "" {
c, err := r.Cookie("passwd")
if err == nil {
passwd = c.Value
}
}
if id == "admin" && passwd == "123456" { // 账号密码判断
cookie := http.Cookie{Name: "id", Value: id, Path: "/", MaxAge: 86400}
http.SetCookie(w, &cookie)
cookie = http.Cookie{Name: "passwd", Value: passwd, Path: "/", MaxAge: 86400}
http.SetCookie(w, &cookie)
next.ServeHTTP(w, r) // 跳转
} else {
fmt.Fprintln(w, "Id or Passwd is Error!") // 不满足条件
}
Info("middleware over") // 中间件结束
})
}
访问地址:http://localhost:8088/?id=admin&passwd=123456