如何将Handle转换为HandleFunc?

时间:2014-12-23 06:02:09

标签: http go routing

我正在制作验证码并遵循示例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:编辑#2: github上的例子工作得很好......只有当我修改路由时,它才会在我尝试生成验证码时返回404。

1 个答案:

答案 0 :(得分:2)

您可以使用http.Handlerhttp.HandlerFunc h转换为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))