Пример #1
0
// 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, &parameters)

	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
0
// 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
0
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
0
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
0
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
0
// 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
0
// 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
0
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, &parameters)

	auth := smtp.PlainAuth("", userName, password, host)

	err = smtp.SendMail(
		fmt.Sprintf("%s:%d", host, port),
		auth,
		userName,
		to,
		buffer.Bytes())

	return err
}
Пример #9
0
// 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
0
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
0
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
0
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
0
// 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
0
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
0
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())
}
Пример #16
0
func watch(r io.Reader) {
	dec := json.NewDecoder(r)
	for {
		event := jsonmessage.JSONMessage{}
		if err := dec.Decode(&event); err != nil {
			if err == io.EOF {
				break
			}
			log.Fatalf("Couldn't decode message: %s", err)
		}
		if *debug {
			log.Printf("< %s:%s", event.ID, event.Status)
		}
		container, err := getContainer(event)
		if err != nil {
			log.Printf("Warning: Couldn't get container %s: %s", event.ID, err)
			continue
		}
		events := hm[event.ID]
		if events == nil {
			events = GetEvents(hm, container)
			if events == nil {
				events = hm["*"]
			}
			if events == nil {
				continue
			}
		}
		commands := events[event.Status]
		if len(commands) == 0 {
			continue
		}
		for _, command := range commands {
			if len(command) == 0 {
				continue
			}
			args := []string{}
			for _, template := range command {
				buf := bytes.NewBufferString("")
				if err := template.Execute(buf, container); err != nil {
					log.Fatalf("Couldn't render template: %s", err)
				}
				args = append(args, buf.String())
			}

			command := exec.Command(args[0], args[1:]...)
			log.Printf("> %s [ %v ]", command.Path, command.Args[1:])
			out, err := command.CombinedOutput()
			if err != nil {
				log.Printf("! ERROR %s: %s", err, out)
				continue
			}
			if out != nil {
				log.Printf("- %s", out)
			}
		}
	}
}
Пример #17
0
func ConfigHandler(w http.ResponseWriter, r *http.Request) (int, error) {
	template, err := template.New(ConfigTemplateName).Parse(ConfigTemplate)
	w.Header().Set("Content-Type", "application/javascript")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return http.StatusInternalServerError, err
	}
	return http.StatusOK, template.Execute(w, getAppConfigJSON())
}
Пример #18
0
func (templateData *TemplateData) getFilename(configuration templateConfiguration) string {
	template, err := template.New(configuration.filenamePattern).Parse(configuration.filenamePattern)
	if err != nil {
		log.Fatalf("Template couldn't be parsed", err)
	}
	var filenameBuffer = &bytes.Buffer{}
	template.Execute(filenameBuffer, templateData)
	return string(filenameBuffer.Bytes())
}
Пример #19
0
func newCommentTemplate(comment *models.Comment) []byte {
	template, _ := template.ParseFiles("templates/mail/newcomment.tmpl")
	var wr bytes.Buffer
	err := template.Execute(&wr, comment)
	if err != nil {
		panic("error sending mail")
	}
	return wr.Bytes()
}
Пример #20
0
func HandleHTTP(muxRouter *mux.Router, version string, router *weave.NetworkRouter, allocator *ipam.Allocator, defaultSubnet address.CIDR, ns *nameserver.Nameserver, dnsserver *nameserver.DNSServer) {
	status := func() WeaveStatus {
		return WeaveStatus{
			version,
			weave.NewNetworkRouterStatus(router),
			ipam.NewStatus(allocator, defaultSubnet),
			nameserver.NewStatus(ns, dnsserver)}
	}
	muxRouter.Methods("GET").Path("/report").Headers("Accept", "application/json").HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			json, err := json.MarshalIndent(status(), "", "    ")
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				Log.Error("Error during report marshalling: ", err)
				return
			}
			w.Header().Set("Content-Type", "application/json")
			w.Write(json)
		})

	muxRouter.Methods("GET").Path("/report").Queries("format", "{format}").HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			funcs := template.FuncMap{
				"json": func(v interface{}) string {
					a, _ := json.Marshal(v)
					return string(a)
				},
			}
			formatTemplate, err := template.New("format").Funcs(funcs).Parse(mux.Vars(r)["format"])
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}
			if err := formatTemplate.Execute(w, status()); err != nil {
				http.Error(w, "error during template execution", http.StatusInternalServerError)
				Log.Error(err)
			}
		})

	defHandler := func(path string, template *template.Template) {
		muxRouter.Methods("GET").Path(path).HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				if err := template.Execute(w, status()); err != nil {
					http.Error(w, "error during template execution", http.StatusInternalServerError)
					Log.Error(err)
				}
			})
	}

	defHandler("/status", statusTemplate)
	defHandler("/status/targets", targetsTemplate)
	defHandler("/status/connections", connectionsTemplate)
	defHandler("/status/peers", peersTemplate)
	defHandler("/status/dns", dnsEntriesTemplate)
	defHandler("/status/ipam", ipamTemplate)

}
Пример #21
0
func (m *IssueManager) printHtml(issues []Issue) (err error) {
	template, err := template.New("issues").Parse(mainTemplate)
	if err != nil {
		return
	}

	template.Execute(os.Stdout, issues)

	return
}
Пример #22
0
func renderDockerfile(dockerFile DockerFile) (string, error) {
	template, err := template.New("dockerfile").Parse(DockerFileTemplate)
	if err != nil {
		return "", err
	}

	doc := new(bytes.Buffer)
	template.Execute(doc, dockerFile)
	return doc.String(), nil
}
Пример #23
0
func render(erd *Erd) {
	template, err := template.ParseFiles("tmpl.dot")
	if err != nil {
		log.Fatalf("Error loading template file: %s\n", err)
	}
	err = template.Execute(os.Stdout, erd)
	if err != nil {
		log.Fatalf("Error generating digraph: %s\n", err)
	}
}
Пример #24
0
// fill text template with data
func fillTemplate(text string, data interface{}) string {
	template, err := template.New("test").Parse(text)
	checkFatal(err)

	buff := bytes.NewBufferString("")
	err = template.Execute(buff, data)
	checkFatal(err)

	return buff.String()
}
func (s *sysv) Install() error {
	confPath, err := s.configPath()
	if err != nil {
		return err
	}
	_, err = os.Stat(confPath)
	if err == nil {
		return fmt.Errorf("Init already exists: %s", confPath)
	}

	f, err := os.Create(confPath)
	if err != nil {
		return err
	}
	defer f.Close()

	path, err := s.execPath()
	if err != nil {
		return err
	}

	var to = &struct {
		*Config
		Path string
	}{
		s.Config,
		path,
	}

	template, err := s.template()
	if err != nil {
		return err
	}
	err = template.Execute(f, to)
	if err != nil {
		return err
	}

	if err = os.Chmod(confPath, 0755); err != nil {
		return err
	}
	for _, i := range [...]string{"2", "3", "4", "5"} {
		if err = os.Symlink(confPath, "/etc/rc"+i+".d/S50"+s.Name); err != nil {
			continue
		}
	}
	for _, i := range [...]string{"0", "1", "6"} {
		if err = os.Symlink(confPath, "/etc/rc"+i+".d/K02"+s.Name); err != nil {
			continue
		}
	}

	return nil
}
Пример #26
0
func main() {
	flag.Parse()

	log.Printf("Fetching %q...", *remote)
	resp, err := http.Get(*remote)
	if err != nil {
		log.Fatalf("failed to download from %q: %s", *remote, err)
	}
	defer resp.Body.Close()

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("failed to read %q: %s", *remote, err)
	}

	ids, cls, err := usbid.ParseIDs(bytes.NewReader(data))
	if err != nil {
		log.Fatalf("failed to parse %q: %s", *remote, err)
	}

	log.Printf("Successfully fetched %q:", *remote)
	log.Printf("  Loaded %d Vendor IDs", len(ids))
	log.Printf("  Loaded %d Class IDs", len(cls))

	rawTemplate, err := ioutil.ReadFile(*dataFile)
	if err != nil {
		log.Fatalf("failed to read template %q: %s", *dataFile)
	}

	template, err := template.New("").Parse(string(rawTemplate))
	if err != nil {
		log.Fatalf("failed to parse template %q: %s", *dataFile, err)
	}

	out, err := os.Create(*outFile)
	if err != nil {
		log.Fatalf("failed to open output file %q: %s", *outFile, err)
	}
	defer out.Close()

	templateData := struct {
		Data      []byte
		Generated time.Time
		RFC3339   string
	}{
		Data:      bytes.Map(sanitize, data),
		Generated: time.Now(),
	}
	if err := template.Execute(out, templateData); err != nil {
		log.Fatalf("failed to execute template: %s", err)
	}

	log.Printf("Successfully wrote %q", *outFile)
}
Пример #27
0
// Handles the index route
func handler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)

	page := Page{
		User: u,
	}

	template, _ := template.ParseFiles("templates/index.html")
	template.Execute(w, page)
}
Пример #28
0
func (c *grimNotificationContext) render(templateString string) (string, error) {
	template, tempErr := template.New("msg").Parse(templateString)
	if tempErr != nil {
		return "", fmt.Errorf("Error parsing notification template: %v", tempErr)
	}

	var doc bytes.Buffer
	if tempErr = template.Execute(&doc, c); tempErr != nil {
		return "", fmt.Errorf("Error applying template: %v", tempErr)
	}

	return doc.String(), nil
}
Пример #29
0
func (ctx Context) Evaluate(tmpl string) (string, error) {
	template, err := template.New(uuid.New()).Parse(tmpl)
	if err != nil {
		panic(fmt.Sprintf("unable parse subject %q as a template", tmpl))
	}

	buffer := bytes.NewBuffer([]byte{})
	if err := template.Execute(buffer, ctx); err != nil {
		panic(fmt.Sprintf("failed to render template [%s]\n[%s]\n", err, ctx))
		return "", err
	}
	return buffer.String(), nil
}
Пример #30
0
func (e *EmailNotifier) TriggerEmail(event *Event, sender EmailSender) error {
	var doc bytes.Buffer

	if len(emailTemplates) == 0 {
		loadEmailTemplates()
	}
	template := emailTemplates[event.Type]
	err := template.Execute(&doc, &EmailEvent{event, e})
	if err != nil {
		return err
	}
	return sender(e, doc)
}