我正在制作驗證碼并遵循此處給出的示例。我需要修改示例以使用 gorilla mux 的路由,因為我的應用程序的其余部分使用它。對于我的生活,我無法弄清楚如何正確地為該示例的第 47 行路由路徑。我下面的結果沒有生成驗證碼......(示例本身工作正常)。對于狗屎和傻笑,我什至嘗試過“http.HandleFunc("/captcha/", captchaHandler)”,但這也不起作用。有什么建議?package mainimport ( "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 []Routetype 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。
1 回答

白板的微信
TA貢獻1883條經(jīng)驗 獲得超3個贊
您可以轉換http.Handler h
一到http.HandlerFunc使用方法表達式:
h.ServeHTTP
您可以直接使用路由Handler方法注冊 Handler,而不是轉換為 HandlerFunc :
router.Methods("GET").Path("/captcha/").Handler(captcha.Server(captcha.StdWidth, captcha.StdHeight))
根據(jù)您的評論和編輯,我認為您需要前綴匹配而不是完全匹配:
router.Methods("GET").PathPrefix("/captcha/").Handler(captcha.Server(captcha.StdWidth, captcha.StdHeight))
- 1 回答
- 0 關注
- 210 瀏覽
添加回答
舉報
0/150
提交
取消