Golang Must示例

说明

golang must示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: text/template

示例#1
文件: type_pointer.go 项目: andyleap/gencode

func init() {
	PointerTemps = template.New("PointerTemps")
	template.Must(PointerTemps.New("marshal").Parse(`
	{
		if {{.Target}} == nil {
			buf[{{if .W.IAdjusted}}i + {{end}}{{.W.Offset}}] = 0
		} else {
			buf[{{if .W.IAdjusted}}i + {{end}}{{.W.Offset}}] = 1
			{{.SubTypeCode}}
			i += {{.SubOffset}}
		}
	}`))
	template.Must(PointerTemps.New("unmarshal").Parse(`
	{
		if buf[{{if .W.IAdjusted}}i + {{end}}{{.W.Offset}}] == 1 {
			if {{.Target}} == nil {
				{{.Target}} = new({{.SubField}})
			}
			{{.SubTypeCode}}
			i += {{.SubOffset}}
		} else {
			{{.Target}} = nil
		}
	}`))
	template.Must(PointerTemps.New("size").Parse(`
	{
		if {{.Target}} != nil {
			{{.SubTypeCode}}
			s += {{.SubOffset}}
		}
	}`))

	template.Must(PointerTemps.New("field").Parse(`*`))
}

示例#2
文件: smoke_test.go 项目: huslage/deis

// Runs a test case and logs the results.
func runTest(t *testing.T, tt *deisTest, cfg *deisTestConfig) {
	// Fill in the command string template from our test configuration.
	var cmdBuf bytes.Buffer
	tmpl := template.Must(template.New("cmd").Parse(tt.cmd))
	if err := tmpl.Execute(&cmdBuf, cfg); err != nil {
		t.Fatal(err)
	}
	cmdString := cmdBuf.String()
	// Change to the target directory if needed.
	if tt.dir != "" {
		// Fill in the directory template from our test configuration.
		var dirBuf bytes.Buffer
		tmpl := template.Must(template.New("dir").Parse(tt.dir))
		if err := tmpl.Execute(&dirBuf, cfg); err != nil {
			t.Fatal(err)
		}
		dir, _ := filepath.Abs(filepath.Join(wd, dirBuf.String()))
		if err := os.Chdir(dir); err != nil {
			t.Fatal(err)
		}
	}
	// TODO: Go's testing package doesn't seem to allow for reporting interim
	// progress--we have to wait until everything completes (or fails) to see
	// anything that was written with t.Log or t.Fatal. Interim output would
	// be extremely helpful here, as this takes a while.
	// Execute the command and log the input and output on error.
	fmt.Printf("%v ... ", strings.TrimSpace(cmdString))
	cmd := exec.Command("sh", "-c", cmdString)
	if out, err := cmd.Output(); err != nil {
		t.Fatalf("%v\nOutput:\n%v", err, string(out))
	} else {
		fmt.Println("ok")
	}
}

示例#3
文件: director_config.go 项目: cloudfoundry-incubator/bosh-fuzz-tests

func (c *DirectorConfig) Write() error {
	directorTemplatePath, err := c.assetsProvider.FullPath("director.yml")
	if err != nil {
		return err
	}

	t := template.Must(template.ParseFiles(directorTemplatePath))
	err = c.saveConfig(c.options.Port, c.DirectorConfigPath(), t)

	if err != nil {
		return err
	}

	cpiTemplatePath, err := c.assetsProvider.FullPath("cpi.sh")
	if err != nil {
		return err
	}

	cpiTemplate := template.Must(template.ParseFiles(cpiTemplatePath))

	err = c.saveCPIConfig(c.CPIPath(), cpiTemplate)

	if err != nil {
		return err
	}

	for i := 1; i <= c.numWorkers; i++ {
		port := c.options.Port + i
		err = c.saveConfig(port, c.WorkerConfigPath(i), t)
		if err != nil {
			return err
		}
	}
	return nil
}

示例#4
文件: admin.go 项目: jiajie999/beego

// AdminIndex is the default http.Handler for admin module.
// it matches url pattern "/".
func adminIndex(rw http.ResponseWriter, r *http.Request) {
	tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
	tmpl = template.Must(tmpl.Parse(indexTpl))
	tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
	data := make(map[interface{}]interface{})
	tmpl.Execute(rw, data)
}

示例#5
文件: main.go 项目: client9/gospell

func init() {
	// we see it so it doesn't use a prefix or include a time stamp.
	stdout = log.New(os.Stdout, "", 0)
	defaultLog = template.Must(template.New("defaultLog").Parse(defaultLogTmpl))
	defaultWord = template.Must(template.New("defaultWord").Parse(defaultWordTmpl))
	defaultLine = template.Must(template.New("defaultLine").Parse(defaultLineTmpl))
}

示例#6
文件: centos_net_manager.go 项目: viovanov/bosh-agent

func (net centosNetManager) writeNetworkInterfaces(dhcpInterfaceConfigurations []DHCPInterfaceConfiguration, staticInterfaceConfigurations []StaticInterfaceConfiguration, dnsServers []string) (bool, error) {
	anyInterfaceChanged := false

	staticConfig := centosStaticIfcfg{}
	staticConfig.DNSServers = newDNSConfigs(dnsServers)
	staticTemplate := template.Must(template.New("ifcfg").Parse(centosStaticIfcfgTemplate))

	for i := range staticInterfaceConfigurations {
		staticConfig.StaticInterfaceConfiguration = &staticInterfaceConfigurations[i]

		changed, err := net.writeIfcfgFile(staticConfig.StaticInterfaceConfiguration.Name, staticTemplate, staticConfig)
		if err != nil {
			return false, bosherr.WrapError(err, "Writing static config")
		}

		anyInterfaceChanged = anyInterfaceChanged || changed
	}

	dhcpTemplate := template.Must(template.New("ifcfg").Parse(centosDHCPIfcfgTemplate))

	for i := range dhcpInterfaceConfigurations {
		config := &dhcpInterfaceConfigurations[i]

		changed, err := net.writeIfcfgFile(config.Name, dhcpTemplate, config)
		if err != nil {
			return false, bosherr.WrapError(err, "Writing dhcp config")
		}

		anyInterfaceChanged = anyInterfaceChanged || changed
	}

	return anyInterfaceChanged, nil
}

示例#7
文件: operation.go 项目: berngp/go-swagger

func init() {
	bv, _ := Asset("templates/server/parameter.gotmpl")
	parameterTemplate = template.Must(template.New("parameter").Parse(string(bv)))

	bm, _ := Asset("templates/server/operation.gotmpl")
	operationTemplate = template.Must(template.New("operation").Parse(string(bm)))
}

示例#8
文件: nats_client_test.go 项目: yingkitw/bosh-agent

func (n *NatsClient) PrepareJob(jobName string) {
	templateID, sha1, err := n.uploadJob(jobName)
	Expect(err).NotTo(HaveOccurred())

	prepareTemplateConfig := PrepareTemplateConfig{
		JobName:                             jobName,
		TemplateBlobstoreID:                 templateID,
		RenderedTemplatesArchiveBlobstoreID: templateID,
		RenderedTemplatesArchiveSHA1:        sha1,
		ReplyTo: senderID,
	}

	buffer := bytes.NewBuffer([]byte{})
	t := template.Must(template.New("prepare").Parse(prepareTemplate))
	err = t.Execute(buffer, prepareTemplateConfig)
	Expect(err).NotTo(HaveOccurred())
	prepareResponse, err := n.SendMessage(buffer.String())
	Expect(err).NotTo(HaveOccurred())

	_, err = n.WaitForTask(prepareResponse["value"]["agent_task_id"], -1)
	Expect(err).ToNot(HaveOccurred())

	buffer.Reset()
	t = template.Must(template.New("apply").Parse(applyTemplate))
	err = t.Execute(buffer, prepareTemplateConfig)
	Expect(err).NotTo(HaveOccurred())
	applyResponse, err := n.SendMessage(buffer.String())
	Expect(err).NotTo(HaveOccurred())

	_, err = n.WaitForTask(applyResponse["value"]["agent_task_id"], -1)
	Expect(err).ToNot(HaveOccurred())
}

示例#9
文件: mgoExample.go 项目: dbmlabs/hellothere

func admin(w http.ResponseWriter, r *http.Request) {
	/* import template
	t, _ := template.ParseFiles("../template/shotchart.html")
	t.Execute(wr io.Writer, p)
	*/

	temp := new(Page)

	values := readDB()
	buf := new(bytes.Buffer)
	for _, value := range values {
		if value.Content == "" {
			continue
		}
		fmt.Println("this is reading from the database the different lines", value)
		t := template.Must(template.New("form").Parse(form))
		t.Execute(buf, value)
	}
	fmt.Println("this is the string of template", buf.String())
	temp.Form = buf.String()
	t := template.Must(template.New("page").Parse(adminPage))
	t.Execute(w, temp)

	//t := template.Must(template.New("form").Parse(form))
	//t.Execute(w, Tom)
	//fmt.Println("this is admin page")
}

示例#10
文件: template.go 项目: vichetuc/boxed

func loadTemplates() {
	templateBox := rice.MustFindBox("templates")
	layout, err := templateBox.String("layout.html")
	if err != nil {
		log.Fatal(err)
	}

	t := []string{
		"index",
		"article",
		"archive",
	}

	for _, tplName := range t {
		tplContent, err := templateBox.String(tplName + ".html")
		if err != nil {
			log.Fatal(err)
		}
		templates[tplName] = template.Must(template.New("layout").Parse(layout + tplContent))
	}

	feed, err := templateBox.String("feed.atom")
	if err != nil {
		log.Fatal(err)
	}

	templates["feed.atom"] = template.Must(template.New("feed.atom").Parse(feed))

	sitemap, err := templateBox.String("sitemap.xml")
	if err != nil {
		log.Fatal(err)
	}

	templates["sitemap.xml"] = template.Must(template.New("sitemap.xml").Parse(sitemap))
}

示例#11
文件: hipchat.go 项目: hamfist/circonus-webhooks-golang

// NewHipchatHandler creates a new by reading the environment
func NewHipchatHandler() *HipchatHandler {
	alertTemplate := os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_ALERT_TEMPLATE")
	if alertTemplate == "" {
		alertTemplate = `Severity {{.Severity}} alert triggered by {{.CheckName}} ({{.MetricName}}: {{.Value}}). {{.URL}}`
	}

	recoveryTemplate := os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_RECOVERY_TEMPLATE")
	if recoveryTemplate == "" {
		recoveryTemplate = `Recovery of {{.CheckName}} ({{.MetricName}}: {{.Value}}). {{.URL}}`
	}

	hh := &HipchatHandler{
		HipchatClient:    &hipchat.Client{AuthToken: os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_API_TOKEN")},
		AlertTemplate:    template.Must(template.New("alert").Parse(alertTemplate)),
		RecoveryTemplate: template.Must(template.New("recovery").Parse(recoveryTemplate)),
		AlertColor:       os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_ALERT_COLOR"),
		RecoveryColor:    os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_RECOVERY_COLOR"),
		From:             os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_FROM"),
	}

	if hh.AlertColor == "" {
		hh.AlertColor = hipchat.ColorRed
	}

	if hh.RecoveryColor == "" {
		hh.RecoveryColor = hipchat.ColorGreen
	}

	if hh.From == "" {
		hh.From = "Circonus"
	}

	return hh
}

示例#12
文件: type_string.go 项目: andyleap/gencode

func init() {
	StringTemps = template.New("StringTemps")

	template.Must(StringTemps.New("marshal").Parse(`
	{
		l := uint64(len({{.Target}}))
		{{.VarIntCode}}
		copy(buf[{{if .W.IAdjusted}}i + {{end}}{{.W.Offset}}:], {{.Target}})
		i += l
	}`))
	template.Must(StringTemps.New("unmarshal").Parse(`
	{
		l := uint64(0)
		{{.VarIntCode}}
		{{.Target}} = string(buf[{{if .W.IAdjusted}}i + {{end}}{{.W.Offset}}:{{if .W.IAdjusted}}i + {{end}}{{.W.Offset}}+l])
		i += l
	}`))
	template.Must(StringTemps.New("size").Parse(`
	{
		l := uint64(len({{.Target}}))
		{{.VarIntCode}}
		s += l
	}`))
	template.Must(StringTemps.New("field").Parse(`string`))
}

示例#13
文件: main.go 项目: myafeier/ws

func main() {
	flag.Parse()
	homeTempl = template.Must(template.ParseFiles(filepath.Join(*assets, "home.html")))
	testTempl = template.Must(template.ParseFiles(filepath.Join(*assets, "test.html")))
	// rc := lib.Newredisc(*redisaddr, 0)
	// err := rc.StartAndGc()
	// if err != nil {
	// 	log.Fatalln(err)
	// }
	db := new(lib.Tips)
	err := db.NewTips(conf.Mysql.Connstr)

	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/test", testHandler)
	h := lib.NewHub()
	go h.Run()
	go h.Productmessage(db)
	go h.ProductHotMessage(db)

	http.Handle("/ws", lib.WsHandler{H: h})
	log.Println("Server is opening")
	err = http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatalln("Listen & Serve Error!")
	}

}

示例#14
文件: type_struct.go 项目: andyleap/gencode

func init() {
	StructTemps = template.New("StructTemps")

	template.Must(StructTemps.New("marshal").Parse(`
	{
		nbuf, err := {{.Target}}.Marshal(buf[{{if .W.IAdjusted}}i + {{end}}{{.W.Offset}}:])
		if err != nil {
			return nil, err
		}
		i += uint64(len(nbuf))
	}`))
	template.Must(StructTemps.New("unmarshal").Parse(`
	{
		ni, err := {{.Target}}.Unmarshal(buf[{{if .W.IAdjusted}}i + {{end}}{{.W.Offset}}:])
		if err != nil {
			return 0, err
		}
		i += ni
	}`))
	template.Must(StructTemps.New("size").Parse(`
	{
		s += {{.Target}}.Size()
	}`))
	template.Must(StructTemps.New("field").Parse(`{{.Struct}}`))
}

示例#15
文件: admin.go 项目: GuyCheung/beego

func execTpl(rw http.ResponseWriter, data map[interface{}]interface{}, tpls ...string) {
	tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
	for _, tpl := range tpls {
		tmpl = template.Must(tmpl.Parse(tpl))
	}
	tmpl.Execute(rw, data)
}

示例#16
文件: type_float.go 项目: andyleap/gencode

func init() {
	FloatTemps = template.New("FloatTemps").Funcs(template.FuncMap{
		"Bytes": func(bits int) int {
			return bits / 8
		},
		"BitRange": func(bits int) []int {
			return []int{0, 8, 16, 24, 32, 40, 48, 56, 64}[0:(bits / 8)]
		},
	})

	template.Must(FloatTemps.New("marshal").Parse(`
	{
		{{if .W.Unsafe}}
		*(*float{{.Bits}})(unsafe.Pointer(&buf[{{if .W.IAdjusted}}i + {{end}}{{.W.Offset}}])) = {{.Target}}
		{{else}}
		v := *(*uint{{.Bits}})(unsafe.Pointer(&({{.Target}})))
		{{range BitRange .Bits}}
		buf[{{if $.W.IAdjusted}}i + {{end}}{{Bytes .}} + {{$.W.Offset}}] = byte(v >> {{.}})
		{{end}}
		{{end}}
	}`))
	template.Must(FloatTemps.New("unmarshal").Parse(`
	{
		{{if .W.Unsafe}}
		{{.Target}} = *(*float{{.Bits}})(unsafe.Pointer(&buf[{{if .W.IAdjusted}}i + {{end}}{{.W.Offset}}]))
		{{else}}
		v := 0{{range BitRange .Bits}} | (uint{{$.Bits}}(buf[{{if $.W.IAdjusted}}i + {{end}}{{Bytes .}} + {{$.W.Offset}}]) << {{.}}){{end}}
		{{.Target}} = *(*float{{.Bits}})(unsafe.Pointer(&v))
		{{end}}
	}`))
	template.Must(FloatTemps.New("field").Parse(`float{{.Bits}}`))
}

示例#17
文件: render.go 项目: ecylmz/gereksiz.us

// Renders a template
func Render(w http.ResponseWriter, r *http.Request, passedTemplate *bytes.Buffer, Statuscode ...int) {
	// Add some HTTP Headers
	if len(Statuscode) == 1 {
		w.WriteHeader(Statuscode[0])
	}

	c := appengine.NewContext(r)
	u := user.Current(c)
	headerdata := HeaderData{}
	if u != nil {
		headerdata.IsLoggedIn = true
		headerdata.Username = u.String()
		if user.IsAdmin(c) {
			headerdata.IsAdmin = true
		}
	}

	// Header
	template.Must(template.ParseFiles("templates/header.html")).Execute(w, headerdata)

	// Now add the passedTemplate
	fmt.Fprintf(w, "%s", string(passedTemplate.Bytes())) // %s = the uninterpreted bytes of the string or slice

	// And now we execute the footer
	template.Must(template.ParseFiles("templates/footer.html")).Execute(w, nil)
}

示例#18
文件: templates.go 项目: elliott-stroud/modelq

func init() {
	tmHeader = template.Must(template.New("header").Parse(header))
	tmStruct = template.Must(template.New("modelStruct").Parse(modelStruct))
	tmObjApi = template.Must(template.New("objApi").Parse(objApi))
	tmQueryApi = template.Must(template.New("queryApi").Parse(queryApi))
	tmManagedObjApi = template.Must(template.New("managedApi").Parse(managedApi))
}

示例#19
文件: help.go 项目: kinvolk/appc-spec

func init() {
	globalUsageTemplate = template.Must(template.New("global_usage").Funcs(templFuncs).Parse(`
NAME:
{{printf "\t%s - %s" .Executable .Description}}

USAGE:
{{printf "\t%s" .Executable}} [global options] <command> [command options] [arguments...]

VERSION:
{{printf "\t%s" .Version}}

COMMANDS:{{range .Commands}}
{{printf "\t%s\t%s" .Name .Summary}}{{end}}

GLOBAL OPTIONS:{{range .Flags}}
{{printOption .Name .DefValue .Usage}}{{end}}

Run "{{.Executable}} help <command>" for more details on a specific command.
`[1:]))
	commandUsageTemplate = template.Must(template.New("command_usage").Funcs(templFuncs).Parse(`
NAME:
{{printf "\t%s - %s" .Cmd.Name .Cmd.Summary}}

USAGE:
{{printf "\t%s %s %s" .Executable .Cmd.Name .Cmd.Usage}}

DESCRIPTION:
{{range $line := descToLines .Cmd.Description}}{{printf "\t%s" $line}}
{{end}}
{{if .CmdFlags}}OPTIONS:{{range .CmdFlags}}
{{printOption .Name .DefValue .Usage}}{{end}}

{{end}}For help on global options run "{{.Executable}} help"
`[1:]))
}

示例#20
文件: generator.go 项目: drborges/appx-cli

func GenerateApi(model *ModelDescriptor) error {
	t := template.Must(template.New("model").Parse(templates.AppxModel))
	output := model.Pkg + "/appx_model_" + model.Name + ".go"
	f, err := os.Create(output)
	if err != nil {
		return err
	}
	defer f.Close()

	if err := t.Execute(f, model); err != nil {
		return err
	}

	t = template.Must(template.New("repo").Funcs(templates.FuncMap).Parse(templates.AppxRepository))
	output = model.Pkg + "/appx_model_" + model.Name + "_repository.go"
	f, err = os.Create(output)
	if err != nil {
		return err
	}
	defer f.Close()

	if err := t.Execute(f, model); err != nil {
		return err
	}

	log.Println("[API] generated for model", model.Name)
	return nil
}

示例#21
文件: admin.go 项目: jiajie999/beego

// ProfIndex is a http.Handler for showing profile command.
// it's in url pattern "/prof" in admin module.
func profIndex(rw http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	command := r.Form.Get("command")
	format := r.Form.Get("format")
	data := make(map[string]interface{})

	var result bytes.Buffer
	if command != "" {
		toolbox.ProcessInput(command, &result)
		data["Content"] = result.String()

		if format == "json" && command == "gc summary" {
			dataJson, err := json.Marshal(data)
			if err != nil {
				http.Error(rw, err.Error(), http.StatusInternalServerError)
				return
			}

			rw.Header().Set("Content-Type", "application/json")
			rw.Write(dataJson)
			return
		}

		data["Title"] = command
		tmpl := template.Must(template.New("dashboard").Parse(dashboardTpl))
		tmpl = template.Must(tmpl.Parse(profillingTpl))
		if command == "gc summary" {
			tmpl = template.Must(tmpl.Parse(gcAjaxTpl))
		} else {

			tmpl = template.Must(tmpl.Parse(defaultScriptsTpl))
		}
		tmpl.Execute(rw, data)
	}
}

示例#22
文件: renderer.go 项目: cloudfoundry-incubator/bosh-fuzz-tests

func (g *renderer) Render(input bftinput.Input, manifestPath string, cloudConfigPath string) error {
	deploymentTemplate := template.Must(template.New("deployment").Parse(DeploymentTemplate))

	buffer := bytes.NewBuffer([]byte{})
	err := deploymentTemplate.Execute(buffer, input)
	if err != nil {
		return bosherr.WrapErrorf(err, "Generating deployment manifest")
	}

	err = g.fs.WriteFile(manifestPath, buffer.Bytes())
	if err != nil {
		return bosherr.WrapErrorf(err, "Saving generated manifest")
	}

	cloudTemplate := template.Must(template.New("cloud-config").Parse(CloudTemplate))

	buffer = bytes.NewBuffer([]byte{})

	err = cloudTemplate.Execute(buffer, input)
	if err != nil {
		return bosherr.WrapErrorf(err, "Generating cloud config")
	}

	err = g.fs.WriteFile(cloudConfigPath, buffer.Bytes())
	if err != nil {
		return bosherr.WrapErrorf(err, "Saving generated cloud config")
	}

	return nil
}

示例#23
文件: smoke_test.go 项目: bdemers/deis

// Runs a test case and logs the results.
func runTest(t *testing.T, tt *deisTest, cfg *utils.DeisTestConfig) {
	// Fill in the command string template from our test configuration.
	var cmdBuf bytes.Buffer
	tmpl := template.Must(template.New("cmd").Parse(tt.cmd))
	if err := tmpl.Execute(&cmdBuf, cfg); err != nil {
		t.Fatal(err)
	}
	cmdString := cmdBuf.String()
	// Change to the target directory if needed.
	if tt.dir != "" {
		// Fill in the directory template from our test configuration.
		var dirBuf bytes.Buffer
		tmpl := template.Must(template.New("dir").Parse(tt.dir))
		if err := tmpl.Execute(&dirBuf, cfg); err != nil {
			t.Fatal(err)
		}
		dir, _ := filepath.Abs(filepath.Join(wd, dirBuf.String()))
		if err := os.Chdir(dir); err != nil {
			t.Fatal(err)
		}
	}
	// Execute the command and log the input and output on error.
	fmt.Printf("%v ... ", strings.TrimSpace(cmdString))
	cmd := exec.Command("sh", "-c", cmdString)
	if out, err := cmd.Output(); err != nil {
		t.Fatalf("%v\nOutput:\n%v", err, string(out))
	} else {
		fmt.Println("ok")
	}
}

示例#24
文件: main.go 项目: nolenroyalty/bangarang

func main() {
	if len(os.Args) > 1 {
		if os.Args[1] == "test" {
			top := template.Must(template.New("top").Parse(NewTestTopTemplate()))
			out(top, nil)
			types := NewTypes()
			t := template.Must(template.New("types").Parse(NewTestTypeTemplate()))
			for _, typ := range types {
				out(t, typ)
			}
			return
		}
	}
	top := template.Must(template.New("top").Parse(NewTopTemplate()))
	out(top, nil)
	types := NewTypes()
	t := template.Must(template.New("types").Parse(NewTypeTemplate()))
	for _, typ := range types {
		if typ.packed {
			out(t, typ)
		}
		typ.packed = false
		out(t, typ)
	}
}

示例#25
文件: main.go 项目: balrajb/goberry

// Generate handler functions based on an API definition.
func generate(api *raml.APIDefinition, genFile string) {

	f, err := os.Create(genFile)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	// Write the header - import statements and root handler.
	f.WriteString(handlerHead)
	// Start the route map (string to handler).
	f.WriteString(mapStart)
	// Add the route map entries.
	e := template.Must(template.New("mapEntry").Parse(mapEntry))
	for name, resource := range api.Resources {
		generateMap("", name, &resource, e, f)
	}
	// Close the route map.
	f.WriteString(mapEnd)
	// Now add the HTTP handlers.
	t := template.Must(template.New("handlerText").Parse(handlerText))
	for name, resource := range api.Resources {
		generateResource("", name, &resource, t, f)
	}
	format(f)
}

示例#26
文件: importer.go 项目: pzduniak/importer

func Render(w http.ResponseWriter, settings *RenderSettings) {
	root_tpl := tt.Must(tt.New("rtt").Parse(settings.RootTemplate))
	repo_tpl := tt.Must(tt.New("rpt").Parse(settings.RepositoryTemplate))

	root_buf := new(bytes.Buffer)
	err := root_tpl.Execute(root_buf, settings.Path)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	repo_buf := new(bytes.Buffer)
	err = repo_tpl.Execute(repo_buf, settings.Path)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	err = PageTemplate.Execute(w, templateInput{
		Root: root_buf.String(),
		Repo: repo_buf.String(),
	})

	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
}

示例#27
文件: main.go 项目: saltmueller/skia-buildbot

func reloadTemplates() {
	// Change the current working directory to two directories up from this source file so that we
	// can read templates and serve static (res/) files.

	if *resourcesDir == "" {
		_, filename, _, _ := runtime.Caller(0)
		*resourcesDir = filepath.Join(filepath.Dir(filename), "../..")
	}
	commitsTemplate = template.Must(template.ParseFiles(
		filepath.Join(*resourcesDir, "templates/commits.html"),
		filepath.Join(*resourcesDir, "templates/header.html"),
	))
	hostsTemplate = template.Must(template.ParseFiles(
		filepath.Join(*resourcesDir, "templates/hosts.html"),
		filepath.Join(*resourcesDir, "templates/header.html"),
	))
	infraTemplate = template.Must(template.ParseFiles(
		filepath.Join(*resourcesDir, "templates/infra.html"),
		filepath.Join(*resourcesDir, "templates/header.html"),
	))
	buildbotDashTemplate = template.Must(template.ParseFiles(
		filepath.Join(*resourcesDir, "templates/buildbot_dash.html"),
		filepath.Join(*resourcesDir, "templates/header.html"),
	))
}

示例#28
文件: main.go 项目: hisayosh/isucon

func buyHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		fmt.Printf("Cannot %s /buy\n", r.Method)
		fmt.Fprintf(w, "Cannot %s /buy", r.Method)
		return
	}

	variation_id := r.PostFormValue("variation_id")
	member_id := r.PostFormValue("member_id")

	//fmt.Fprintf(w, "buy:\n")
	//fmt.Printf("  variation_id: %s\n", variation_id)
	//fmt.Printf("  member_id: %s\n", member_id)

	model := db.Buy(variation_id, member_id)

	if model.Result == true {
		var t = template.Must(template.ParseFiles("template/buy_complete.html"))
		if err := t.Execute(w, model); err != nil {
			fmt.Println(err.Error())
		}
	} else {
		var t = template.Must(template.ParseFiles("template/buy_soldout.html"))
		if err := t.Execute(w, model); err != nil {
			fmt.Println(err.Error())
		}
	}
}

示例#29
文件: serveHTTP.go 项目: wjessop/UXSS_PoC

func serveHome() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if req.URL.Path != "/" {
			http.Error(w, "Not found", 404)
			return
		}

		if *template_file != "" {
			if _, err := os.Stat(*template_file); os.IsNotExist(err) {
				panic("Custom template file not found")
			}

			homeTempl = template.Must(template.ParseFiles(*template_file))
		} else {
			bytes, err := Asset("data/templates/home.html")
			if err != nil {
				panic(err)
			}
			homeTempl = template.Must(template.New("home").Parse(string(bytes)))
		}

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		homeTempl.Execute(w, template_vars)
	})
}

示例#30
文件: main.go 项目: hheld/AltReactScaffolding

func generateProject(htmlSettings HtmlTemplateSettings, packageSettings PackageTemplateSettings) {
	htmlTemplate, _ := Asset("client/index.html")
	packageTemplate, _ := Asset("package.json")

	htmlTempl := template.Must(template.New("").Parse(string(htmlTemplate)))
	packageTempl := template.Must(template.New("").Parse(string(packageTemplate)))

	appFolder := packageSettings.AppName

	RestoreAssets(appFolder, "")

	htmlFile, _ := os.Create(path.Join(appFolder, "client", "index.html"))
	htmlFileWriter := bufio.NewWriter(htmlFile)
	defer func() {
		htmlFileWriter.Flush()
		htmlFile.Close()
	}()

	packageFile, _ := os.Create(path.Join(appFolder, "package.json"))
	packageFileWriter := bufio.NewWriter(packageFile)
	defer func() {
		packageFileWriter.Flush()
		packageFile.Close()
	}()

	htmlTempl.Execute(htmlFileWriter, htmlSettings)
	packageTempl.Execute(packageFileWriter, packageSettings)
}

展开阅读全文