doushuangai9733 2014-12-23 06:02
浏览 93
已采纳

如何将Handle转换为HandleFunc?

I am making a captcha and am following the example given here. I need to modify the example to use gorilla mux's routing as the rest of my app uses that. For the life of me I can't figure out how to correctly route the path for line 47 of that example. What I have below results in no captcha generated...(the example itself works fine). For shits & giggles I've even tried "http.HandleFunc("/captcha/", captchaHandler)" but that doesn't work either. Any suggestions?

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!
")
    } else {
        io.WriteString(w, "Great job, human! You solved the captcha.
")
    }
    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: To be clearer "doesn't work" isn't helpful. It returns a 404 error.

EDIT #2: The example on github works fine....its only when I modify the route that it returns a 404 when I try to generate a captcha.

  • 写回答

1条回答 默认 最新

  • dtl85148 2014-12-23 06:26
    关注

    You can convert the http.Handler h to a http.HandlerFunc using the method expression:

    h.ServeHTTP
    

    Instead of converting to a HandlerFunc, you can register the Handler directly using the route Handler method:

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

    Based on your comments and edits, I think you want a prefix match instead of an exact match:

    router.Methods("GET").PathPrefix("/captcha/").Handler(captcha.Server(captcha.StdWidth, captcha.StdHeight))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀