Google的“执行”和范围/功能

在golang.org提供的示例服务器之一中:


package main


import (

    "flag"

    "http"

    "io"

    "log"

    "template"

)


var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18

var fmap = template.FormatterMap{

    "html": template.HTMLFormatter,

    "url+html": UrlHtmlFormatter,

}

var templ = template.MustParse(templateStr, fmap)


func main() {

    flag.Parse()

    http.Handle("/", http.HandlerFunc(QR))

    err := http.ListenAndServe(*addr, nil)

    if err != nil {

        log.Exit("ListenAndServe:", err)

    }

}


func QR(c *http.Conn, req *http.Request) {

    templ.Execute(req.FormValue("s"), c)

}


func UrlHtmlFormatter(w io.Writer, v interface{}, fmt string) {

    template.HTMLEscape(w, []byte(http.URLEscape(v.(string))))

}



const templateStr = `

<html>

<head>

<title>QR Link Generator</title>

</head>

<body>

{.section @}

<img src="http://chart.apis.google.com/chart?chs=300x300&cht=qr&choe=UTF- 8&chl={@|url+html}"

/>

<br>

{@|html}

<br>

<br>

{.end}

<form action="/" name=f method="GET"><input maxLength=1024 size=70

name=s value="" title="Text to QR Encode"><input type=submit

value="Show QR" name=qr>

</form>

</body>

</html>

`  

为什么template.HTMLEscape(w, []byte(http.URLEscape(v.(string))))包含在其中UrlHtmlFormatter?为什么不能直接链接到它"url+html"?


另外,如何更改func QR以接受参数值?我想要它做的是接受一个命令行标志代替req *http.Request...预先感谢...


aluckdog
浏览 226回答 2
2回答

森林海

您编辑了原始问题以添加第二个问题。另外,如何更改func QR以接受参数值?我想要它做的是接受一个命令行标志来代替req * http.Request。如果您阅读《 Go编程语言规范》,§Types(包括§Function类型),您将发现Go具有强大的静态类型,包括函数类型。尽管这不能保证捕获所有错误,但通常会捕获使用无效,不匹配的函数签名的尝试。您没有告诉我们为什么要以QR似乎是任意和反复无常的方式更改的函数签名,以使其不再是有效的HandlerFunc类型,从而保证程序甚至无法编译。我们只能猜测您想完成什么。也许就这么简单:您想http.Request基于运行时参数修改。也许是这样的:// Note: flag.Parse() in func main() {...}var qrFlag = flag.String("qr", "", "function QR parameter")func QR(c *http.Conn, req *http.Request) {&nbsp; &nbsp; if len(*qrFlag) > 0 {&nbsp; &nbsp; &nbsp; &nbsp; // insert code here to use the qr parameter (qrFlag)&nbsp; &nbsp; &nbsp; &nbsp; // to modify the http.Request (req)&nbsp; &nbsp; }&nbsp; &nbsp; templ.Execute(req.FormValue("s"), c)}也许不是!谁知道?
打开App,查看更多内容
随时随地看视频慕课网APP