1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| package main
import ( "encoding/json" "log" "math/rand" "net/http" "time"
"gopkg.in/gomail.v2" )
const ( smtpHost = "smtp.example.com" smtpPort = 587 email = "your@email.com" password = "yourpassword" )
var codeStore = make(map[string]string)
func generateCode(length int) string { rand.Seed(time.Now().UnixNano()) digits := "0123456789" code := "" for i := 0; i < length; i++ { code += string(digits[rand.Intn(len(digits))]) } return code }
func sendEmail(to string, code string) error { m := gomail.NewMessage() m.SetHeader("From", email) m.SetHeader("To", to) m.SetHeader("Subject", "您的验证码") m.SetBody("text/html", "<h2>验证码</h2><p>您的验证码是:<b>"+code+"</b></p><p>有效期 5 分钟。</p>")
d := gomail.NewDialer(smtpHost, smtpPort, email, password) return d.DialAndSend(m) }
func sendCodeHandler(w http.ResponseWriter, r *http.Request) { type req struct { Email string `json:"email"` } var in req if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Email == "" { http.Error(w, "invalid request", http.StatusBadRequest) return }
code := generateCode(6) codeStore[in.Email] = code
if err := sendEmail(in.Email, code); err != nil { http.Error(w, "send mail failed: "+err.Error(), http.StatusInternalServerError) return }
resp := map[string]string{"msg": "验证码已发送"} w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(resp) }
func verifyCodeHandler(w http.ResponseWriter, r *http.Request) { type req struct { Email string `json:"email"` Code string `json:"code"` } var in req if err := json.NewDecoder(r.Body).Decode(&in); err != nil { http.Error(w, "invalid request", http.StatusBadRequest) return }
ok := codeStore[in.Email] == in.Code resp := map[string]bool{"ok": ok} w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(resp) }
func main() { http.HandleFunc("/send-code", sendCodeHandler) http.HandleFunc("/verify-code", verifyCodeHandler) http.Handle("/", http.FileServer(http.Dir(".")))
log.Println("Server running at http://localhost:8080") log.Fatal(http.ListenAndServe(":8080", nil)) }
|