2010-03-18 3 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> 
` 

template.HTMLEscape(w, []byte(http.URLEscape(v.(string))))UrlHtmlFormatter에 포함되어? "url+html"에 직접 연결할 수없는 이유는 무엇입니까?

또한 어떻게 func QR을 매개 변수 값을 허용하도록 변경할 수 있습니까? 무엇을 할 내가 원하는 것은 기능 template.HTMLEscape에 대한

+0

내가 묻는 질문에 대한 모든 답변에 감사드립니다 ... – danwoods

답변

1

서명은 ... ... req *http.Request 대신에 미리 감사를 명령 줄 플래그를 받아 들일 수 있습니다 :

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

의 유형 선언 template.FormatterMap위한 :

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

따라서 FormatterMap지도 요소 값 함수에 대한 서명은 다음

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

함수는 HTMLEscape 함수에 FormatterMap map 요소 값 함수 시그니처를 제공하는 래퍼입니다.

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

이 두 번째 질문을 추가하기 위해 원래 질문을 편집했습니다.

또한 어떻게 func QR을 매개 변수 값으로 변경할 수 있습니까? 그것은 내가 할 싶습니다 req * http.Request 대신 명령 줄 플래그를 받아들입니다. 당신이 §Function types 포함 The Go Programming Language Specification, §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

관련 문제