Go语言 如何将句柄转换为HandleFunc?

dced5bon  于 2022-12-16  发布在  Go
关注(0)|答案(2)|浏览(113)

我正在制作一个验证码,并遵循这里给出的例子。我需要修改这个例子,以使用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>
`

EDIT#1:更清楚地说,“不工作”是没有帮助的。它返回一个404错误。
编辑#2:github上的示例工作正常...只有当我修改路由时,当我试图生成验证码时,它才会返回404。

44u64gxh

44u64gxh1#

可以使用方法表达式将http.Handler h转换为http.HandlerFunc:

h.ServeHTTP

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

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

根据您的注解和编辑,我认为您需要前缀匹配而不是完全匹配:

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

r1wp621o2#

对主题问题的直接回答就是简单地保持原样。

func(w http.ResponseWriter, r *http.Request, p map[string]string) {
    youhttp.Handler().ServeHTTP(w, r)
}

相关问题