源码:
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

本文介绍了一个使用Go语言编写的简单Web应用,该应用包含一个认证中间件,用于处理用户的身份验证过程。通过检查URL参数或Cookies中的用户名和密码来决定是否允许访问资源。
6万+

被折叠的 条评论
为什么被折叠?



