from https://www.cnblogs.com/janbar/archive/2021/04/01/14607659.html
文章非常棒,无废话干货
package main import ( "flag" "fmt" "net/http" "golang.org/x/crypto/bcrypt" ) func main() { pass := flag.String("p", "admin", "check password") flag.Parse() password := []byte(*pass) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write(html) }) http.HandleFunc("/users/login", func(w http.ResponseWriter, r *http.Request) { hashedPassword := r.FormValue("pass") fmt.Println(hashedPassword) err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), password) if err != nil { fmt.Fprintln(w, err) } else { fmt.Fprintln(w, "password ok") } }) http.ListenAndServe(":8080", nil) } var html = []byte(`<!DOCTYPE html> <html> <head> <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/dcodeIO/bcrypt.js/dist/bcrypt.min.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/jquery/jquery@3.2.1/dist/jquery.min.js"></script> </head> <body> <p>密码: <input id="pass" type="password" name="pass"/></p> <button type="button" onclick="login()">提交</button> <script type="text/javascript"> function login() { /* https://github.com/dcodeIO/bcrypt.js */ var bcrypt = dcodeIO.bcrypt; /* 将密码加密提交 *// $.post(‘/users/login‘,{pass: bcrypt.hashSync($(‘#pass‘).val(), 8)}, function(result) { alert(result); } ); } </script> </body> </html>`)