Golang Http Middleware 判断 增加cookie

来源:互联网 发布:上海迅销网络招聘真假 编辑:程序博客网 时间:2024/05/24 07:38


源码:

package mainimport ("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

0 0
原创粉丝点击