为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
aluckdog 2021-03-30 13:12:49
在golang.org提供的示例服务器之一中:package mainimport (    "flag"    "http"    "io"    "log"    "template")var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18var 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=70name=s value="" title="Text to QR Encode"><input type=submitvalue="Show QR" name=qr></form></body></html>`  为什么template.HTMLEscape(w, []byte(http.URLEscape(v.(string))))包含在其中UrlHtmlFormatter?为什么不能直接链接到它"url+html"?另外,如何更改func QR以接受参数值?我想要它做的是接受一个命令行标志代替req *http.Request...预先感谢...
查看完整描述

2 回答

?
森林海

TA贡献2011条经验 获得超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) {

    if len(*qrFlag) > 0 {

        // insert code here to use the qr parameter (qrFlag)

        // to modify the http.Request (req)

    }

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

}

也许不是!谁知道?


查看完整回答
反对 回复 2021-04-26
  • 2 回答
  • 0 关注
  • 224 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信