gpt4 book ai didi

http - 如何将句柄转换为 HandleFunc?

转载 作者:IT王子 更新时间:2023-10-29 02:05:38 28 4
gpt4 key购买 nike

我正在制作验证码并按照示例 given here .我需要修改示例以使用 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)
}
*/
var routes = Routes{
Route{"GET", "/", showFormHandler},
Route{"POST", "/process", processFormHandler},
Route{"GET", "/captcha/", captchaHandler},
}
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
router.Methods(route.Method).Path(route.Pattern).Handler(handler)
}
//router.Methods("GET").Path("/captcha/").HandlerFunc(captcha.Server(captcha.StdWidth, captcha.StdHeight))

port := ":8666"
log.Println("Listening at", port)
log.Fatal(http.ListenAndServe(port, router))
}

const formTemplateSrc = `<!doctype html>
<head><title>Captcha Example</title></head>
<body>
<script>
function setSrcQuery(e, q) {
var src = e.src;
var p = src.indexOf('?');
if (p >= 0) {
src = src.substr(0, p);
}
e.src = src + "?" + q
}
function playAudio() {
var le = document.getElementById("lang");
var lang = le.options[le.selectedIndex].value;
var e = document.getElementById('audio')
setSrcQuery(e, "lang=" + lang)
e.style.display = 'block';
e.autoplay = 'true';
return false;
}
function changeLang() {
var e = document.getElementById('audio')
if (e.style.display == 'block') {
playAudio();
}
}
function reload() {
setSrcQuery(document.getElementById('image'), "reload=" + (new Date()).getTime());
setSrcQuery(document.getElementById('audio'), (new Date()).getTime());
return false;
}
</script>
<select id="lang" onchange="changeLang()">
<option value="en">English</option>
<option value="ru">Russian</option>
<option value="zh">Chinese</option>
</select>
<form action="/process" method=post>
<p>Type the numbers you see in the picture below:</p>
<p><img id=image src="/captcha/{{.CaptchaId}}.png" alt="Captcha image"></p>
<a href="#" onclick="reload()">Reload</a> | <a href="#" onclick="playAudio()">Play Audio</a>
<audio id=audio controls style="display:none" src="/captcha/{{.CaptchaId}}.wav" preload=none>
You browser doesn't support audio.
<a href="/captcha/download/{{.CaptchaId}}.wav">Download file</a> to play it in the external player.
</audio>
<input type=hidden name=captchaId value="{{.CaptchaId}}"><br>
<input name=captchaSolution>
<input type=submit value=Submit>
</form>
`

编辑#1:更清楚地说“不起作用”没有帮助。它返回 404 错误。

编辑#2:github 上的示例工作正常....只有当我修改路由时,它才会在我尝试生成验证码时返回 404。

最佳答案

您可以转换 http.Handler hhttp.HandlerFunc使用 method expression :

h.ServeHTTP

您可以直接使用路由 Handler 注册处理程序,而不是转换为 HandlerFunc。方法:

router.Methods("GET").Path("/captcha/").Handler(captcha.Server(captcha.StdWidth, captcha.StdHeight))

根据您的评论和编辑,我认为您想要一个 prefix match而不是完全匹配:

router.Methods("GET").PathPrefix("/captcha/").Handler(captcha.Server(captcha.StdWidth, captcha.StdHeight))

关于http - 如何将句柄转换为 HandleFunc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27614932/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com