2010-03-18 51 views
1

。在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> 
` 

爲什麼是包含在UrlHtmlFormattertemplate.HTMLEscape(w, []byte(http.URLEscape(v.(string))))?爲什麼不能直接鏈接到"url+html"

另外,我怎麼能改變func QR接受參數值?我想讓它做的是接受命令行標誌代替req *http.Request ...在此先感謝...

+0

我很感激所有的迴應,我得到的問題,我問... – danwoods 2010-03-22 02:10:29

回答

1

的簽名功能template.HTMLEscape是:

func(w io.Writer, s []byte) 

的類型聲明爲template.FormatterMap是:

type FormatterMap map[string]func(io.Writer, interface{}, string) 

因此,對於FormatterMap地圖元素值函數的簽名是:

func(io.Writer, interface{}, string) 

UrlHtmlFormatter函數是爲HTMLEscape函數FormatterMap映射元素值函數簽名提供的封裝函數。

func UrlHtmlFormatter(w io.Writer, v interface{}, fmt string) { 
    template.HTMLEscape(w, []byte(http.URLEscape(v.(string)))) 
} 
0

您編輯了您的原始問題以添加第二個問題。

另外,我怎樣才能將func QR更改爲 接受參數值?我想 它接受一個命令行 標誌代替req * http.Request。

如果你讀The Go Programming Language Specification§Types,包括§Function types,你會看到,圍棋具有很強的靜態類型,包括函數類型。儘管這並不能保證捕獲所有錯誤,但通常會捕獲嘗試使用無效的,不匹配的函數簽名。

你不告訴我們,爲什麼要改變函數簽名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) 
} 

也許不是!誰知道?

+0

對不起。改變QR功能的目的是爲它傳遞一個變量作爲參數。 – danwoods 2010-03-22 02:07:23