我正在制作验证码并遵循此处给出的示例。我需要修改示例以使用 gorilla mux 的路由,因为我的应用程序的其余部分使用它。对于我的生活,我无法弄清楚如何正确地为该示例的第 47 行路由路径。我下面的结果没有生成验证码......(示例本身工作正常)。对于狗屎和傻笑,我什至尝试过“http.HandleFunc("/captcha/", captchaHandler)”,但这也不起作用。有什么建议?
package main
import (
"github.com/dchest/captcha"
"github.com/gorilla/mux"
"io"
"log"
"net/http"
"text/template"
)
var formTemplate = template.Must(template.New("example").Parse(formTemplateSrc))
func showFormHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
d := struct {
CaptchaId string
}{
captcha.New(),
}
if err := formTemplate.Execute(w, &d); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func processFormHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if !captcha.VerifyString(r.FormValue("captchaId"), r.FormValue("captchaSolution")) {
io.WriteString(w, "Wrong captcha solution! No robots allowed!\n")
} else {
io.WriteString(w, "Great job, human! You solved the captcha.\n")
}
io.WriteString(w, "<br><a href='/'>Try another one</a>")
}
func captchaHandler(w http.ResponseWriter, r *http.Request) {
captcha.Server(captcha.StdWidth, captcha.StdHeight)
}
type Routes []Route
type Route struct {
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
func main() {
/*
http.HandleFunc("/", showFormHandler)
http.HandleFunc("/process", processFormHandler)
//http.HandleFunc("/captcha/", captchaHandler) // doesn't work
http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight))
fmt.Println("Server is at localhost:8666")
if err := http.ListenAndServe(":8666", nil); err != nil {
log.Fatal(err)
}
*/
编辑#1:更清楚地说“不起作用”没有帮助。它返回 404 错误。
编辑 #2:github 上的示例工作正常......只有当我修改路由时,当我尝试生成验证码时它返回 404。
白板的微信
相关分类