本文整理汇总了Golang中text/template.Execute函数的典型用法代码示例。如果您正苦于以下问题:Golang Execute函数的具体用法?Golang Execute怎么用?Golang Execute使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Execute函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: sendRegoEmail
// Send a registration email for a given user
func sendRegoEmail(user UserData) {
msg, err := ioutil.ReadFile("regomail.txt")
if err != nil {
log.Println(err)
}
parameters := struct {
Server string
ValidationKey string
}{
REGOSERVER,
GetMD5HexHash(user.Email + user.Password),
}
buffer := new(bytes.Buffer)
template := template.Must(template.New("regoTemplate").Parse(string(msg)))
template.Execute(buffer, ¶meters)
fmtMsg := buffer.String()
err = SendEmail("Welcome to the Kriegsspiel Server",
[]string{user.Email},
fmtMsg)
if err != nil {
log.Fatal(err)
}
log.Println("Sent registration email to ", user.Email)
}
示例2: writeConfig
// writeConfig writes the config to disk
func (r *templateRouter) writeConfig() error {
//write out any certificate files that don't exist
for k, cfg := range r.state {
if err := r.writeCertificates(&cfg); err != nil {
return fmt.Errorf("error writing certificates for %s: %v", k, err)
}
cfg.Status = ServiceAliasConfigStatusSaved
r.state[k] = cfg
}
for path, template := range r.templates {
file, err := os.Create(path)
if err != nil {
return fmt.Errorf("error creating config file %s: %v", path, err)
}
data := templateData{
WorkingDir: r.dir,
State: r.state,
ServiceUnits: r.serviceUnits,
DefaultCertificate: r.defaultCertificatePath,
PeerEndpoints: r.peerEndpoints,
StatsUser: r.statsUser,
StatsPassword: r.statsPassword,
StatsPort: r.statsPort,
}
if err := template.Execute(file, data); err != nil {
file.Close()
return fmt.Errorf("error executing template for file %s: %v", path, err)
}
file.Close()
}
return nil
}
示例3: RenderTmpl
func (r *Context) RenderTmpl() {
if r.tplName != "" {
var fileName string
ext := path.Ext(r.tplName)
if ext == "."+TemplateExt || ext == ".html" || ext == ".xhtml" {
fileName = r.tplName
template := template.New(fileName)
var dir string
if ext == "."+TemplateExt {
dir = templateDir
} else {
dir = webApp
}
if _, err := template.ParseFiles(path.Join(dir, fileName)); err != nil {
http.Error(r.Response, err.Error(), http.StatusInternalServerError)
} else {
err := template.Execute(r.Response, r.data)
if err != nil {
http.Error(r.Response, err.Error(), http.StatusInternalServerError)
}
}
} else {
http.NotFound(r.Response, r.Request)
}
}
}
示例4: writeConf
func writeConf() error {
template, err := template.New(filepath.Base(config.Nginx_template)).ParseFiles(config.Nginx_template)
if err != nil {
return err
}
parent := filepath.Dir(config.Nginx_config)
tmpFile, err := ioutil.TempFile(parent, ".nginx.conf.tmp-")
defer tmpFile.Close()
err = template.Execute(tmpFile, config)
if err != nil {
return err
}
config.LastUpdates.LastConfigRendered = time.Now()
err = checkConf(tmpFile.Name())
if err != nil {
return err
}
err = os.Rename(tmpFile.Name(), config.Nginx_config)
if err != nil {
return err
}
return nil
}
示例5: spec
func spec(group string) {
template := template.Must(template.New("tmpl").Parse(configurationTemplate))
any := false
if group == "all" {
any = true
}
definitions := GetConfig().GetDescription()
found := false
for _, definition := range definitions {
if definition.Name == group || any {
err := template.Execute(os.Stdout, definition)
if err != nil {
fmt.Fprintf(os.Stderr, "executing template:", err)
}
found = true
}
}
if !found {
fmt.Fprintf(os.Stderr, "unable to find spec for '%s'", group)
}
}
示例6: Install
// Install will create the necessary upstart conf file in the correct location
// config: The configuration for the service
func (service *linuxUpstartService) Install(config *Config) error {
confPath := service.getServiceFilePath()
_, err := os.Stat(confPath)
if err == nil {
return fmt.Errorf("Init already exists: %s", confPath)
}
file, err := os.Create(confPath)
if err != nil {
return err
}
defer file.Close()
parameters := &struct {
ExecutableName string
WorkingDirectory string
Name string
DisplayName string
LongDescription string
}{
service.config.ExecutableName,
service.config.WorkingDirectory,
service.config.Name,
service.config.DisplayName,
service.config.LongDescription,
}
template := template.Must(template.New("upstartScript").Parse(installScript()))
return template.Execute(file, parameters)
}
示例7: ScheduleCsvReportHandler
// Generates a CSV-formatted report of the match schedule.
func ScheduleCsvReportHandler(w http.ResponseWriter, r *http.Request) {
if !UserIsReader(w, r) {
return
}
vars := mux.Vars(r)
matches, err := db.GetMatchesByType(vars["type"])
if err != nil {
handleWebErr(w, err)
return
}
// Don't set the content type as "text/csv", as that will trigger an automatic download in the browser.
w.Header().Set("Content-Type", "text/plain")
template, err := template.ParseFiles("templates/schedule.csv")
if err != nil {
handleWebErr(w, err)
return
}
err = template.Execute(w, matches)
if err != nil {
handleWebErr(w, err)
return
}
}
示例8: SendEmail
func SendEmail(host string, port int, userName string, password string, to []string, subject string, message string) (err error) {
defer catchPanic(&err, "SendEmail")
parameters := struct {
From string
To string
Subject string
Message string
}{
userName,
strings.Join([]string(to), ","),
subject,
message,
}
buffer := new(bytes.Buffer)
template := template.Must(template.New("emailTemplate").Parse(emailScript()))
template.Execute(buffer, ¶meters)
auth := smtp.PlainAuth("", userName, password, host)
err = smtp.SendMail(
fmt.Sprintf("%s:%d", host, port),
auth,
userName,
to,
buffer.Bytes())
return err
}
示例9: ApplyTemplate
// ApplyTemplate creates and renders a template from the given config template
func ApplyTemplate(config []byte) ([]byte, error) {
template, err := NewTemplate(config)
if err != nil {
return nil, err
}
return template.Execute()
}
示例10: serveHijackerClient
func serveHijackerClient(w http.ResponseWriter, r *http.Request) {
template, err := template.ParseFiles("./hijack/hijack.js")
if err != nil {
w.WriteHeader(404)
w.Write([]byte{})
return
}
w.Header().Set("Content-type", "application/javascript")
url := ""
if *settings.secure {
url += "wss://"
} else {
url += "ws://"
}
url += *settings.domain
if !*settings.secure {
url += *settings.port
}
url += "/hijacker/ws"
template.Execute(w, map[string]string{"url": url})
}
示例11: generateClient
func generateClient(schema []client.Schema) error {
template, err := template.ParseFiles("client.template")
if err != nil {
return err
}
output, err := os.Create(path.Join(CLIENT_OUTPUT_DIR, "generated_client.go"))
if err != nil {
return err
}
defer output.Close()
buffer := make([]client.Schema, 0, len(schema))
for _, val := range schema {
if !(val.Id == "collection" || val.Id == "resource" || val.Id == "schema") {
val.Id = strings.ToUpper(val.Id[:1]) + val.Id[1:]
buffer = append(buffer, val)
}
}
result := map[string]interface{}{
"schemas": buffer,
}
err = template.Execute(output, result)
return err
}
示例12: expandHandler
func expandHandler(w http.ResponseWriter, r *http.Request) {
const url_prefix = "/expand/"
if r.URL.Path == url_prefix {
rootHandler(w, r)
return
}
c := appengine.NewContext(r)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
path := r.URL.Path[len(url_prefix):]
template, err := LoadTemplates(path, contextTemplateLoader{c})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
r.ParseForm()
if err := template.Execute(w, r.Form); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
示例13: renderEnvValue
// Searches the OS environment, then the route options, then the render context
// Env for a given key, then uses the value (or the provided default value)
// as template text, which is then rendered in the given context.
// The rendered result is returned - or the default value on any errors.
func (a *CloudwatchAdapter) renderEnvValue(
envKey string, context *RenderContext, defaultVal string) string {
finalVal := defaultVal
if logspoutEnvVal := os.Getenv(envKey); logspoutEnvVal != "" {
finalVal = logspoutEnvVal // use $envKey, if set
}
if routeOptionsVal, exists := a.Route.Options[envKey]; exists {
finalVal = routeOptionsVal
}
if containerEnvVal, exists := context.Env[envKey]; exists {
finalVal = containerEnvVal // or, $envKey from container!
}
template, err := template.New("template").Parse(finalVal)
if err != nil {
log.Println("cloudwatch: error parsing template", finalVal, ":", err)
return defaultVal
} else { // render the templates in the generated context
var renderedValue bytes.Buffer
err = template.Execute(&renderedValue, context)
if err != nil {
log.Printf("cloudwatch: error rendering template %s : %s\n",
finalVal, err)
return defaultVal
}
finalVal = renderedValue.String()
}
return finalVal
}
示例14: main
func main() {
flag.Parse()
data := Data{
"SVG -> PDF",
time.Now().Format("_2 Jan 2006 15:04:05"),
20150803,
"Строка кириллицей",
true,
}
var err error
// Load template from file
template, err := template.ParseFiles(*inputFile)
chk(err)
// Store template to buffer
buf := new(bytes.Buffer)
err = template.Execute(buf, data)
chk(err)
// Convert via external application
// Install before use
// # apt-get install librsvg2-bin
// or
// # apt-get install inkscape
var cmd *exec.Cmd
if *converter == "inkscape" {
fmt.Println("Generate via inkscape")
cmd = exec.Command("inkscape", "--without-gui", "/dev/stdin", "--export-pdf=/dev/stdout")
if *outputPng != "" {
cmd.Args = append(cmd.Args, "--export-png", *outputPng)
}
} else {
fmt.Println("Generate via rsvg-convert")
cmd = exec.Command("rsvg-convert", "-f", "pdf")
}
cmd.Stdin = bytes.NewReader(buf.Bytes())
// Write pdf to file
out, err := os.OpenFile(*outputFile, os.O_CREATE|os.O_WRONLY, 0666)
chk(err)
defer out.Close()
cmd.Stdout = out
timeStart := time.Now().UnixNano()
err = cmd.Run() // Syncronous run external application
chk(err)
timeEnd := time.Now().UnixNano()
fmt.Println("Conversion time (ms)", (timeEnd-timeStart)/1000000)
// Open output file using the OS's default application
open.Run(*outputFile)
}
示例15: ConfigHandler
func ConfigHandler(w http.ResponseWriter, r *http.Request) (int, error) {
template, err := template.New(ConfigTemplateName).Parse(ConfigTemplate)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return http.StatusInternalServerError, err
}
return http.StatusOK, template.Execute(w, getAppConfigJSON())
}