本文整理汇总了Golang中text/template.Must函数的典型用法代码示例。如果您正苦于以下问题:Golang Must函数的具体用法?Golang Must怎么用?Golang Must使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Must函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: init
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: runTest
// 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: Write
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: adminIndex
// 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: init
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: writeNetworkInterfaces
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: init
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: PrepareJob
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: admin
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: loadTemplates
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: NewHipchatHandler
// 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: init
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
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: init
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: execTpl
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)
}