原生go语言web系统登录模块实现
原生go语言web系统登录模块实现。刚学go几天,网上原生go写web系统的教程很少。我基本借鉴php的经验,边猜边写。登录成功后跳转不不知道为啥不能成功。网上找了一堆解决方法都不行。或者只能用ajax吧。这坑先留着。。。
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/gorilla/mux" "html/template" "net/http" ) //申明模板变量,自动引入模板包 var templates *template.Template func main() { r := mux.NewRouter() RegisterRoutes(r) //路由 //引入模板 templates = template.Must(template.ParseGlob("templates/*.html")) //引入静态资源 fs := http.FileServer(http.Dir("./static")) r.PathPrefix("/static/").Handler(http.StripPrefix("/static", fs)) http.ListenAndServe(":5000", r) } //登录页面 GET func loginHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) err := templates.ExecuteTemplate(w, "login.html", nil) if err != nil { return } } //登录逻辑 POST func doLoginHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) //获取表单值 r.ParseForm() username := r.PostForm.Get("name") password := r.PostForm.Get("pwd") //数据库匹配 var db *sql.DB db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/p4_stu") if err != nil { panic(err) } var count int64 var err1 error err1 = db.QueryRow("select count(*) from users where `username`=? and `password`=? ", username, password).Scan(&count) if err1 != nil { panic(err1) } //匹配结果处理 if int(count) >= 1 { w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "<h1>登录成功!</h1>") //以下跳转代码,不知道为啥不能成功! //w.Header().Set("Cache-Control", "must-revalidate, no-store") //w.Header().Set("Content-Type", " text/html;charset=UTF-8") //w.Header().Set("Location", "http://127.0.0.1:5000") //跳转地址设置 ////http.Redirect(w, r, "http://www.baidu.com", http.StatusFound) //跳转到百度 //w.WriteHeader(307) } else { w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "<h1>用户名或者密码错误</h1>") } } //路由 var RegisterRoutes = func(router *mux.Router) { router.HandleFunc("/dologin", doLoginHandler).Methods("POST") router.HandleFunc("/login", loginHandler).Methods("GET") }