如何将Handle转换为HandleFunc?

huangapple go评论71阅读模式
英文:

How do I convert a Handle to a HandleFunc?

问题

我正在制作一个验证码,并且正在按照这里给出的示例进行操作。我需要修改示例代码,以便在我的应用程序中使用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:
更明确地说,"doesn't work"并不具有帮助性。它返回一个404错误。

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

英文:

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 (
&quot;github.com/dchest/captcha&quot;
&quot;github.com/gorilla/mux&quot;
&quot;io&quot;
&quot;log&quot;
&quot;net/http&quot;
&quot;text/template&quot;
)
var formTemplate = template.Must(template.New(&quot;example&quot;).Parse(formTemplateSrc))
func showFormHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != &quot;/&quot; {
http.NotFound(w, r)
return
}
d := struct {
CaptchaId string
}{
captcha.New(),
}
if err := formTemplate.Execute(w, &amp;d); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func processFormHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set(&quot;Content-Type&quot;, &quot;text/html; charset=utf-8&quot;)
if !captcha.VerifyString(r.FormValue(&quot;captchaId&quot;), r.FormValue(&quot;captchaSolution&quot;)) {
io.WriteString(w, &quot;Wrong captcha solution! No robots allowed!\n&quot;)
} else {
io.WriteString(w, &quot;Great job, human! You solved the captcha.\n&quot;)
}
io.WriteString(w, &quot;&lt;br&gt;&lt;a href=&#39;/&#39;&gt;Try another one&lt;/a&gt;&quot;)
}
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(&quot;/&quot;, showFormHandler)
http.HandleFunc(&quot;/process&quot;, processFormHandler)
//http.HandleFunc(&quot;/captcha/&quot;, captchaHandler) // doesn&#39;t work
http.Handle(&quot;/captcha/&quot;, captcha.Server(captcha.StdWidth, captcha.StdHeight))
fmt.Println(&quot;Server is at localhost:8666&quot;)
if err := http.ListenAndServe(&quot;:8666&quot;, nil); err != nil {
log.Fatal(err)
}
*/
var routes = Routes{
Route{&quot;GET&quot;, &quot;/&quot;, showFormHandler},
Route{&quot;POST&quot;, &quot;/process&quot;, processFormHandler},
Route{&quot;GET&quot;, &quot;/captcha/&quot;, 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(&quot;GET&quot;).Path(&quot;/captcha/&quot;).HandlerFunc(captcha.Server(captcha.StdWidth, captcha.StdHeight))
port := &quot;:8666&quot;
log.Println(&quot;Listening at&quot;, port)
log.Fatal(http.ListenAndServe(port, router))
}
const formTemplateSrc = `&lt;!doctype html&gt;
&lt;head&gt;&lt;title&gt;Captcha Example&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;
&lt;script&gt;
function setSrcQuery(e, q) {
var src  = e.src;
var p = src.indexOf(&#39;?&#39;);
if (p &gt;= 0) {
src = src.substr(0, p);
}
e.src = src + &quot;?&quot; + q
}
function playAudio() {
var le = document.getElementById(&quot;lang&quot;);
var lang = le.options[le.selectedIndex].value;
var e = document.getElementById(&#39;audio&#39;)
setSrcQuery(e, &quot;lang=&quot; + lang)
e.style.display = &#39;block&#39;;
e.autoplay = &#39;true&#39;;
return false;
}
function changeLang() {
var e = document.getElementById(&#39;audio&#39;)
if (e.style.display == &#39;block&#39;) {
playAudio();
}
}
function reload() {
setSrcQuery(document.getElementById(&#39;image&#39;), &quot;reload=&quot; + (new Date()).getTime());
setSrcQuery(document.getElementById(&#39;audio&#39;), (new Date()).getTime());
return false;
}
&lt;/script&gt;
&lt;select id=&quot;lang&quot; onchange=&quot;changeLang()&quot;&gt;
&lt;option value=&quot;en&quot;&gt;English&lt;/option&gt;
&lt;option value=&quot;ru&quot;&gt;Russian&lt;/option&gt;
&lt;option value=&quot;zh&quot;&gt;Chinese&lt;/option&gt;
&lt;/select&gt;
&lt;form action=&quot;/process&quot; method=post&gt;
&lt;p&gt;Type the numbers you see in the picture below:&lt;/p&gt;
&lt;p&gt;&lt;img id=image src=&quot;/captcha/{{.CaptchaId}}.png&quot; alt=&quot;Captcha image&quot;&gt;&lt;/p&gt;
&lt;a href=&quot;#&quot; onclick=&quot;reload()&quot;&gt;Reload&lt;/a&gt; | &lt;a href=&quot;#&quot; onclick=&quot;playAudio()&quot;&gt;Play Audio&lt;/a&gt;
&lt;audio id=audio controls style=&quot;display:none&quot; src=&quot;/captcha/{{.CaptchaId}}.wav&quot; preload=none&gt;
You browser doesn&#39;t support audio.
&lt;a href=&quot;/captcha/download/{{.CaptchaId}}.wav&quot;&gt;Download file&lt;/a&gt; to play it in the external player.
&lt;/audio&gt;
&lt;input type=hidden name=captchaId value=&quot;{{.CaptchaId}}&quot;&gt;&lt;br&gt;
&lt;input name=captchaSolution&gt;
&lt;input type=submit value=Submit&gt;
&lt;/form&gt;
`

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

得分: 2

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

h.ServeHTTP

除了转换为HandlerFunc,你还可以直接使用路由的Handler方法注册Handler:

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

根据你的评论和编辑,我认为你想要一个前缀匹配而不是一个精确匹配:

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

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(&quot;GET&quot;).Path(&quot;/captcha/&quot;).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(&quot;GET&quot;).PathPrefix(&quot;/captcha/&quot;).Handler(captcha.Server(captcha.StdWidth, captcha.StdHeight))

答案2

得分: 0

直接回答一个主题问题的方法就是按原样返回。

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

The direct answer to a topic question is simply as is.

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

huangapple
  • 本文由 发表于 2014年12月23日 14:02:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/27614932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定