当前位置: 首页>>代码示例>>Golang>>正文


Golang template.Must函数代码示例

本文整理汇总了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)
}
开发者ID:Alexandur,项目名称:ppopdr,代码行数:58,代码来源:start.go

示例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()
	}
}
开发者ID:aubonbeurre,项目名称:gcc,代码行数:9,代码来源:escape_test.go

示例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")
		}
	}
}
开发者ID:Altece,项目名称:Go-Go-Gadget-Repo,代码行数:48,代码来源:main.go

示例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)
	}
}
开发者ID:victorcoder,项目名称:mango,代码行数:29,代码来源:show_errors.go

示例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)
	}
}
开发者ID:jordanorelli,项目名称:superchat,代码行数:26,代码来源:main.go

示例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)
			}
		}
	}
}
开发者ID:jordanorelli,项目名称:superchat,代码行数:28,代码来源:main.go

示例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)
}
开发者ID:aubonbeurre,项目名称:gcc,代码行数:7,代码来源:escape_test.go

示例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))}
}
开发者ID:adamsxu,项目名称:twister,代码行数:7,代码来源:template.go

示例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)
	}
}
开发者ID:ghostnotes,项目名称:HelloGo,代码行数:8,代码来源:staticfile.go

示例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
}
开发者ID:tbocs,项目名称:webapp-experiments,代码行数:8,代码来源:tbocsincloud.go

示例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))
}
开发者ID:adamsxu,项目名称:twister,代码行数:8,代码来源:chat.go

示例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)
}
开发者ID:stereobooster,项目名称:site,代码行数:10,代码来源:reports.go

示例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)
}
开发者ID:surma-dump,项目名称:trendinghubs,代码行数:11,代码来源:main.go

示例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))
}
开发者ID:vablaya,项目名称:gopp-cs345,代码行数:12,代码来源:godoc.go

示例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")
}
开发者ID:tobi,项目名称:tinny,代码行数:17,代码来源:error.go


注:本文中的template.Must函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。