當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。