本文整理汇总了Golang中template.Must函数的典型用法代码示例。如果您正苦于以下问题:Golang Must函数的具体用法?Golang Must怎么用?Golang Must使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Must函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: init
func init() {
// Articles
goweb.MapRest("/article/category/{category_id}", new(controller.ArticleController))
// Articles
goweb.MapRest("/article", new(controller.ArticleController))
// Comments
goweb.MapRest("/comment", new(controller.CommentController))
// Categories
goweb.MapRest("/category", new(controller.CategoryController))
// Logs
goweb.MapRest("/log", new(controller.LogController))
// Search
goweb.MapRest("/search", new(controller.SearchController))
// Documentation wadl
goweb.MapFunc("/documentation/wadl", func(c *goweb.Context) {
var docTemplate = template.Must(template.ParseFile("webservice/views/wadl.wadl"))
if err := docTemplate.Execute(c.ResponseWriter, nil); err != nil {
c.RespondWithErrorMessage(err.String(), http.StatusInternalServerError)
}
})
// WADL in XML voor XML viewer
goweb.MapFunc("/documentation/wadl/xml", func(c *goweb.Context) {
var docTemplate = template.Must(template.ParseFile("webservice/views/wadl.xml"))
if err := docTemplate.Execute(c.ResponseWriter, nil); err != nil {
c.RespondWithErrorMessage(err.String(), http.StatusInternalServerError)
}
})
// Documentation
goweb.MapFunc("/documentation", func(c *goweb.Context) {
var docTemplate = template.Must(template.ParseFile("webservice/views/documentation.html"))
if err := docTemplate.Execute(c.ResponseWriter, nil); err != nil {
c.RespondWithErrorMessage(err.String(), http.StatusInternalServerError)
}
})
// Index
goweb.MapFunc("/", func(c *goweb.Context) {
var indexTemplate = template.Must(template.ParseFile("webservice/views/index.html"))
if err := indexTemplate.Execute(c.ResponseWriter, nil); err != nil {
c.RespondWithErrorMessage(err.String(), http.StatusInternalServerError)
}
})
// use the default Go handler
http.Handle("/", goweb.DefaultHttpHandler)
}
示例2: BenchmarkEscapedExecute
func BenchmarkEscapedExecute(b *testing.B) {
tmpl := template.Must(Escape(template.Must(template.New("t").Parse(`<a onclick="alert('{{.}}')">{{.}}</a>`))))
var buf bytes.Buffer
b.ResetTimer()
for i := 0; i < b.N; i++ {
tmpl.Execute(&buf, "foo & 'bar' & baz")
buf.Reset()
}
}
示例3: main
/*
* Run the program
*
* Usage:
* ./ls [args] directory_name
*
* possible args:
* -R: go through directories recursively
* -n: print with information
* -t: sort files by modification time
*
* if no arguments are getting, print out alphabetically with 1 file
* per line
*/
func main() {
var R *bool
var n *bool
var t *bool
R = flag.Bool("R", false, "go through directories recursively")
n = flag.Bool("n", false, "print with information")
t = flag.Bool("t", false, "sort files by modification time")
flag.Parse()
args := flag.Args()
if len(args) == 0 {
args = []string{"./"}
}
defer func() {
if r := recover(); r != nil {
fmt.Fprintln(os.Stderr, "Invalid Arguments")
}
}()
temp := template.Must(template.New("ls").Parse("{{.Mode}} {{printf `%3d` .Nlink}} {{.Uid}} {{.Gid}} {{printf `%7d` .Size}} {{.Mtime}} {{.Name}}\n"))
for _, arg := range args {
if data, error := ls.Ls(arg, *R, *t); error == nil {
path := data[0][0].Name
if strings.HasSuffix(path, "/") {
path = path[0 : len(path)-1]
}
printFiles(flag.NArg(), data, path, n, temp)
} else {
fmt.Fprintln(os.Stderr, "File or directory not found")
}
}
}
示例4: ShowErrors
func ShowErrors(templateString string) Middleware {
if templateString == "" {
templateString = `
<html>
<body>
<p>
{{.Error|html}}
</p>
</body>
</html>
`
}
errorTemplate := template.Must(template.New("error").Parse(templateString))
return func(env Env, app App) (status Status, headers Headers, body Body) {
defer func() {
if err := recover(); err != nil {
buffer := bytes.NewBufferString("")
errorTemplate.Execute(buffer, struct{ Error string }{fmt.Sprintf("%s", err)})
status = 500
headers = Headers{}
body = Body(buffer.String())
}
}()
return app(env)
}
}
示例5: NewRollOff
func NewRollOff(w http.ResponseWriter, r *http.Request) {
rollingUser := ParseUser(r)
entry := &RollOffEntry{User: rollingUser, Score: rand.Intn(100) + 1}
rolloff := &RollOff{Id: randomString(20), Open: true}
rolloff.AddEntry(entry)
go rolloff.Cycle()
rolloffs = append(rolloffs, rolloff)
for elem := room.Users.Front(); elem != nil; elem = elem.Next() {
go func(e *list.Element) {
var tName string
u := e.Value.(*User)
if u == rollingUser {
tName = "templates/roll-off/rolling-user.html"
} else {
tName = "templates/roll-off/other-users.html"
}
t := template.Must(template.ParseFile(tName))
m := NewMessage("system", "", "system")
t.Execute(m, entry)
u.c <- m
}(elem)
}
}
示例6: EnterRollOff
func EnterRollOff(w http.ResponseWriter, r *http.Request) {
id := r.URL.Path[len("/roll-off-entry/"):]
fmt.Println("User wishes to enter rolloff ", id)
rollingUser := ParseUser(r)
entry := &RollOffEntry{User: rollingUser, Score: rand.Intn(100) + 1}
for _, r := range rolloffs {
fmt.Println("Checking rolloff ", r.Id)
if r.Id == id {
r.AddEntry(entry)
for elem := room.Users.Front(); elem != nil; elem = elem.Next() {
go func(e *list.Element) {
var tName string
u := e.Value.(*User)
if u == rollingUser {
tName = "templates/roll-off/user-joins.html"
} else {
tName = "templates/roll-off/other-user-joins.html"
}
t := template.Must(template.ParseFile(tName))
m := NewMessage("system", "", "system")
t.Execute(m, entry)
u.c <- m
}(elem)
}
}
}
}
示例7: TestEscapeErrorsNotIgnorable
func TestEscapeErrorsNotIgnorable(t *testing.T) {
var b bytes.Buffer
tmpl := template.Must(template.New("dangerous").Parse("<a"))
Escape(tmpl)
err := tmpl.Execute(&b, nil)
expectExecuteFailure(t, &b, err)
}
示例8: parseTemplate
func parseTemplate(filename string) *Template {
return &Template{
t: template.Must(template.New(filename).
Funcs(template.FuncMap{"item": itemFormatter}).
ParseFile(path.Join("template", filename))),
mimeType: mime.TypeByExtension(path.Ext(filename))}
}
示例9: handler
func handler(w http.ResponseWriter, r *http.Request) {
name := r.FormValue("name")
htmltemplate := template.Must(template.New("html").Parse(templateHTML))
err := htmltemplate.Execute(w, name)
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
}
}
示例10: root
func root(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
clientTemplate := template.Must(template.ParseFile("client.html"))
token_value := strconv.Itoa(rand.Int())
token_key, _ := channel.Create(c, token_value)
clientTemplate.Execute(w, token_key)
map_clients[token_key] = token_value
}
示例11: main
func main() {
chatTempl = template.Must(template.New("chat").Parse(chatStr))
go hub()
server.Run(":8080",
web.NewRouter().
Register("/", "GET", chatFrameHandler).
Register("/ws", "GET", chatWsHandler))
}
示例12: init
func init() {
for _, name := range []string{"500", "404", "report"} {
tmpl := template.Must(template.New(name).ParseFile("jshint/templates/" + name + ".html"))
templates[name] = tmpl
}
http.HandleFunc("/reports/save/", save)
http.HandleFunc("/reports/", show)
http.HandleFunc("/", notFound)
}
示例13: generateFeed
func generateFeed(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
feed := GetFeed(c)
if feed == nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/rss+xml")
tpl := template.Must(template.New("feed").Parse(rawtemplate))
tpl.Execute(w, feed)
}
示例14: readTemplate
func readTemplate(name string) *template.Template {
path := filepath.Join(*goroot, "lib", "godoc", name)
if *templateDir != "" {
defaultpath := path
path = filepath.Join(*templateDir, name)
if _, err := fs.Stat(path); err != nil {
log.Print("readTemplate:", err)
path = defaultpath
}
}
return template.Must(template.New(name).Funcs(fmap).ParseFile(path))
}
示例15: init
func init() {
layout := template.New("error template")
layout.Funcs(fmap)
tmpl = template.Must(layout.Parse(`
<!DOCTYPE html>
<html>
<head><title>Error: {{.title | html}}</title></head>
<body style='font-style:sans-serif;font-size:10pt;background:#eee'>
<div style='border:1px solid #999;background:white;margin: 50px auto;padding:1em 3em;width:600px'>
<h2>{{.title | html | n2br}}</h2>
<pre style='background:#222;color:#eee;padding:8px 5px;border:1px solid #666'>{{.error | html | n2br}}</pre>
</div>
</body>
</html>`))
ex = regexp.MustCompile("\n")
}