Esempio n. 1
0
File: ip.go Progetto: delaemon/go-ip
func accessLog(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		bufbody := new(bytes.Buffer)
		bufbody.ReadFrom(req.Body)
		body := bufbody.String()
		line := accessLogLine{
			req.RemoteAddr,
			req.Header.Get("Content-Type"),
			req.URL.Path,
			req.URL.RawQuery,
			req.Method, body, req.UserAgent(),
		}
		tmpl, err := template.New("line").Parse(accessLogTemplate)
		if err != nil {
			panic(err)
		}
		bufline := new(bytes.Buffer)
		err = tmpl.Execute(bufline, line)
		if err != nil {
			panic(err)
		}

		logFile := fmt.Sprintf("./log/access/%d%02d%02d.log", accessTime.Year(), accessTime.Month(), accessTime.Day())
		f, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			panic(err)
		}
		log.SetOutput(f)
		log.Printf(bufline.String())

		handler.ServeHTTP(w, req)
	})
}
Esempio n. 2
0
func ExampleTemplate() {
	// Define a template.
	const letter = `
Dear {{.Name}},
{{if .Attended}}
It was a pleasure to see you at the wedding.{{else}}
It is a shame you couldn't make it to the wedding.{{end}}
{{with .Gift}}Thank you for the lovely {{.}}.
{{end}}
Best wishes,
Josie
`

	// Prepare some data to insert into the template.
	type Recipient struct {
		Name, Gift string
		Attended   bool
	}
	var recipients = []Recipient{
		{"Aunt Mildred", "bone china tea set", true},
		{"Uncle John", "moleskin pants", false},
		{"Cousin Rodney", "", false},
	}

	// Create a new template and parse the letter into it.
	t := template.Must(template.New("letter").Parse(letter))

	// Execute the template for each recipient.
	for _, r := range recipients {
		err := t.Execute(os.Stdout, r)
		if err != nil {
			log.Println("executing template:", err)
		}
	}

	// Output:
	// Dear Aunt Mildred,
	//
	// It was a pleasure to see you at the wedding.
	// Thank you for the lovely bone china tea set.
	//
	// Best wishes,
	// Josie
	//
	// Dear Uncle John,
	//
	// It is a shame you couldn't make it to the wedding.
	// Thank you for the lovely moleskin pants.
	//
	// Best wishes,
	// Josie
	//
	// Dear Cousin Rodney,
	//
	// It is a shame you couldn't make it to the wedding.
	//
	// Best wishes,
	// Josie
}
Esempio n. 3
0
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		temp, err := template.New("upload").ParseGlob("templates/*")
		if err != nil {
			fmt.Fprintf(w, "Error: ", err)
			return
		}
		temp.ExecuteTemplate(w, "upload", nil)

	case "POST":
		fmt.Fprintf(w, "Not implemented")
	}
}
Esempio n. 4
0
func main() {
	r, err := os.Open("values.json")
	fatalIfError(err)
	defer r.Close()

	v := []Value{}
	err = json.NewDecoder(r).Decode(&v)
	fatalIfError(err)

	valueName := func(v *Value) string {
		if v.Name != "" {
			return v.Name
		}
		return strings.Title(v.Type)
	}

	t, err := template.New("genvalues").Funcs(template.FuncMap{
		"Lower": strings.ToLower,
		"Format": func(v *Value) string {
			if v.Format != "" {
				return v.Format
			}
			return "fmt.Sprintf(\"%v\", *f)"
		},
		"ValueName": func(v *Value) string {
			name := valueName(v)
			return strings.ToLower(name[0:1]) + name[1:] + "Value"
		},
		"Name": valueName,
		"Plural": func(v *Value) string {
			if v.Plural != "" {
				return v.Plural
			}
			return valueName(v) + "List"
		},
	}).Parse(tmpl)
	fatalIfError(err)

	w, err := os.Create("values_generated.go")
	fatalIfError(err)
	defer w.Close()

	err = t.Execute(w, v)
	fatalIfError(err)

	err = exec.Command("goimports", "-w", "values_generated.go").Run()
	fatalIfError(err)
}
Esempio n. 5
0
// ConfigureMaster configures the master node.
func (k *K8s) ConfigureMaster(sshFingerprint string) error {
	f, err := ioutil.TempFile("", "mcc")
	if err != nil {
		return err
	}

	t, err := template.New("cloud config").Parse(masterCloudConfig)
	if err != nil {
		return err
	}

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

	err = f.Close()
	if err != nil {
		return err
	}
	defer func() {
		os.Remove(f.Name())
	}()

	name := fmt.Sprintf("cs-%s-master-%s", k.name, k.region)
	log.Printf("booting master: %s", name)

	out, err := k.doit("droplet", "create", name,
		"--output", "json",
		"--image", nodeImage,
		"--region", k.region,
		"--size", nodeSize,
		"--ssh-keys", sshFingerprint,
		"--user-data-file", f.Name(),
		"--wait")
	if err != nil {
		return err
	}

	log.Printf("output %s\n", out)

	return nil
}
Esempio n. 6
0
// CreateWorkerKeyPair creates key pairs for workers.
func (ca *CA) CreateWorkerKeyPair(workerFQDN, workerIP string) error {
	p := filepath.Join(ca.dir, "worker-openssl.cnf")
	f, err := os.Create(p)
	if err != nil {
		return err
	}

	t, err := template.New("worker openssl config").Parse(workerOpensslConfig)
	if err != nil {
		return err
	}

	args := map[string]interface{}{
		"WorkerIP": workerIP,
	}

	err = t.Execute(f, args)
	if err != nil {
		return err
	}

	key := fmt.Sprintf("%s-worker-key.pem", workerFQDN)
	csr := fmt.Sprintf("%s-worker.csr", workerFQDN)
	crt := fmt.Sprintf("%s-worker.pem", workerFQDN)

	err = ca.openssl("genrsa", "-out", key, "2048")
	if err != nil {
		return err
	}

	err = ca.openssl("req", "-new", "-key", key,
		"-out", csr, "-subj", "/CN=${WORKER_FQDN}",
		"-config", "worker-openssl.cnf")
	if err != nil {
		return err
	}

	return ca.openssl("x509", "-req", "-in", csr,
		"-CA", "ca.pem", "-CAkey", "ca-key.pem", "-CAcreateserial",
		"-out", crt, "-days", "365",
		"-extensions", "v3_req", "-extfile", "worker-openssl.cnf")
}
Esempio n. 7
0
// This example demonstrates a custom function to process template text.
// It installs the strings.Title function and uses it to
// Make Title Text Look Good In Our Template's Output.
func ExampleTemplate_func() {
	// First we create a FuncMap with which to register the function.
	funcMap := template.FuncMap{
		// The name "title" is what the function will be called in the template text.
		"title": strings.Title,
	}

	// A simple template definition to test our function.
	// We print the input text several ways:
	// - the original
	// - title-cased
	// - title-cased and then printed with %q
	// - printed with %q and then title-cased.
	const templateText = `
Input: {{printf "%q" .}}
Output 0: {{title .}}
Output 1: {{title . | printf "%q"}}
Output 2: {{printf "%q" . | title}}
`

	// Create a template, add the function map, and parse the text.
	tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText)
	if err != nil {
		log.Fatalf("parsing: %s", err)
	}

	// Run the template to verify the output.
	err = tmpl.Execute(os.Stdout, "the go programming language")
	if err != nil {
		log.Fatalf("execution: %s", err)
	}

	// Output:
	// Input: "the go programming language"
	// Output 0: The Go Programming Language
	// Output 1: "The Go Programming Language"
	// Output 2: "The Go Programming Language"
}
Esempio n. 8
0
// CreateAPIServerKeyPair creates a keypair for the api server.
func (ca *CA) CreateAPIServerKeyPair(masterIP string) error {
	p := filepath.Join(ca.dir, "openssl.cnf")
	f, err := os.Create(p)
	if err != nil {
		return err
	}

	t, err := template.New("openssl config").Parse(opensslConfig)
	if err != nil {
		return err
	}

	args := map[string]interface{}{
		"ServiceIP":  ca.serviceIP,
		"MasterHost": masterIP,
	}

	err = t.Execute(f, args)
	if err != nil {
		return err
	}

	err = ca.openssl("genrsa", "-out", "apiserver-key.pem", "2048")
	if err != nil {
		return err
	}

	err = ca.openssl("req", "-new", "-key", "apiserver-key.pem", "-out", "apiserver.csr",
		"-subj", "/CN=kube-apiserver", "-config", "openssl.cnf")
	if err != nil {
		return err
	}

	return ca.openssl("x509", "-req", "-in", "apiserver.csr", "-CA", "ca.pem",
		"-CAkey", "ca-key.pem", "-CAcreateserial", "-out", "apiserver.pem",
		"-days", "365", "-extensions", "v3_req", "-extfile", "openssl.cnf")
}
Esempio n. 9
0
// UsageForContextWithTemplate is the base usage function. You generally don't need to use this.
func (a *Application) UsageForContextWithTemplate(context *ParseContext, indent int, tmpl string) error {
	width := guessWidth(a.writer)
	funcs := template.FuncMap{
		"Indent": func(level int) string {
			return strings.Repeat(" ", level*indent)
		},
		"Wrap": func(indent int, s string) string {
			buf := bytes.NewBuffer(nil)
			indentText := strings.Repeat(" ", indent)
			doc.ToText(buf, s, indentText, indentText, width-indent)
			return buf.String()
		},
		"FormatFlag": formatFlag,
		"FlagsToTwoColumns": func(f []*FlagModel) [][2]string {
			rows := [][2]string{}
			haveShort := false
			for _, flag := range f {
				if flag.Short != 0 {
					haveShort = true
					break
				}
			}
			for _, flag := range f {
				if !flag.Hidden {
					rows = append(rows, [2]string{formatFlag(haveShort, flag), flag.Help})
				}
			}
			return rows
		},
		"RequiredFlags": func(f []*FlagModel) []*FlagModel {
			requiredFlags := []*FlagModel{}
			for _, flag := range f {
				if flag.Required == true {
					requiredFlags = append(requiredFlags, flag)
				}
			}
			return requiredFlags
		},
		"OptionalFlags": func(f []*FlagModel) []*FlagModel {
			optionalFlags := []*FlagModel{}
			for _, flag := range f {
				if flag.Required == false {
					optionalFlags = append(optionalFlags, flag)
				}
			}
			return optionalFlags
		},
		"ArgsToTwoColumns": func(a []*ArgModel) [][2]string {
			rows := [][2]string{}
			for _, arg := range a {
				s := "<" + arg.Name + ">"
				if !arg.Required {
					s = "[" + s + "]"
				}
				rows = append(rows, [2]string{s, arg.Help})
			}
			return rows
		},
		"FormatTwoColumns": func(rows [][2]string) string {
			buf := bytes.NewBuffer(nil)
			formatTwoColumns(buf, indent, indent, width, rows)
			return buf.String()
		},
		"FormatTwoColumnsWithIndent": func(rows [][2]string, indent, padding int) string {
			buf := bytes.NewBuffer(nil)
			formatTwoColumns(buf, indent, padding, width, rows)
			return buf.String()
		},
		"FormatAppUsage":     formatAppUsage,
		"FormatCommandUsage": formatCmdUsage,
		"IsCumulative": func(value Value) bool {
			r, ok := value.(remainderArg)
			return ok && r.IsCumulative()
		},
		"Char": func(c rune) string {
			return string(c)
		},
	}
	t, err := template.New("usage").Funcs(funcs).Parse(tmpl)
	if err != nil {
		return err
	}
	var selectedCommand *CmdModel
	if context.SelectedCommand != nil {
		selectedCommand = context.SelectedCommand.Model()
	}
	ctx := templateContext{
		App:   a.Model(),
		Width: width,
		Context: &templateParseContext{
			SelectedCommand: selectedCommand,
			FlagGroupModel:  context.flags.Model(),
			ArgGroupModel:   context.arguments.Model(),
		},
	}
	return t.Execute(a.writer, ctx)
}
Esempio n. 10
0
File: main.go Progetto: mantyr/gorx
func main() {
	kingpin.Parse()
	t := template.Must(template.New("react").Funcs(template.FuncMap{
		"TypeName": func(s string) string {
			st, err := parser.ParseExpr(s)
			kingpin.FatalIfError(err, "invalid type %q", s)
			return strings.Join(typeName(st), "")
		},
		"IsNumeric": func(v string) bool {
			switch v {
			case "byte", "uint", "int", "uint8", "int8", "uint16", "int16", "uint32",
				"int32", "uint64", "int64", "float32", "float64":
				return true
			}
			return false
		},
	}).Parse(reactTemplate))
	// We always include int. As an aside, this kind of verbosity is my
	// biggest peeve with Go. 10 lines compared to basically any other
	// language:
	//
	// 		if *typesArg.Contains("int") { ... }
	//
	// Super annoying.
	found := false
	for _, s := range *typesArg {
		if s == "int" {
			found = true
			break
		}
	}
	if !found {
		*typesArg = append(*typesArg, "int")
	}
	cmd := exec.Command("goimports")
	if *debugFlag {
		cmd = exec.Command("cat")
	}
	outputFile := os.Stdout
	if *outputFlag != "" {
		dir := filepath.Dir(*outputFlag)
		var err error
		outputFile, err = ioutil.TempFile(dir, ".gorx-")
		kingpin.FatalIfError(err, "")
		defer os.Remove(outputFile.Name())
	}
	cmd.Stdout = outputFile
	stdin, err := cmd.StdinPipe()
	kingpin.FatalIfError(err, "")
	kingpin.FatalIfError(cmd.Start(), "")
	err = t.Execute(stdin, &Context{
		Package:       *packageArg,
		Types:         *typesArg,
		Imports:       *importsFlag,
		MaxReplaySize: *maxReplayFlag,
	})
	kingpin.FatalIfError(err, "")
	stdin.Close()
	kingpin.FatalIfError(cmd.Wait(), "")
	outputFile.Close()
	if *outputFlag != "" {
		kingpin.FatalIfError(os.Rename(outputFile.Name(), *outputFlag), "")
	}
}
Esempio n. 11
0
func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, usage, os.Args[0], os.Args[0])
		flag.PrintDefaults()
	}
	flag.Parse()
	if *source == "" || *rpcType == "" {
		fatalf("expected --source and --type")
	}
	if *target == "" {
		parts := strings.Split(*source, ".")
		parts = parts[:len(parts)-1]
		*target = strings.Join(parts, ".") + "rpc.go"
	}

	fileset := token.NewFileSet()
	f, err := parser.ParseFile(fileset, *source, nil, 0)
	if err != nil {
		fatalf("failed to parse %s: %s", *source, err)
	}
	imports := map[string]bool{}
	if *importsFlag != "" {
		for _, imp := range strings.Split(*importsFlag, ",") {
			imports[imp] = true
		}
	}
	if *packageFlag == "" {
		*packageFlag = f.Name.Name
	}
	if *serviceName == "" {
		*serviceName = *rpcType
	}
	gen := &RPCGen{
		Service: *serviceName,
		Type:    *rpcType,
		RPCType: *rpcClientTypeFlag,
		Package: *packageFlag,
		Imports: imports,
		fileset: fileset,
	}
	ast.Walk(gen, f)
	funcs := map[string]interface{}{
		"publicfields":         func(fields []*Type) string { return FieldList(fields, "", "\n\t", true, true) },
		"refswithprefix":       func(prefix string, fields []*Type) string { return FieldList(fields, prefix, ", ", false, false) },
		"publicrefswithprefix": func(prefix string, fields []*Type) string { return FieldList(fields, prefix, ", ", false, true) },
		"functionargs":         func(fields []*Type) string { return FieldList(fields, "", ", ", true, false) },
	}
	t, err := template.New("rpc").Funcs(funcs).Parse(rpcTemplate)
	if err != nil {
		fatalf("failed to parse template: %s", err)
	}
	out, err := os.Create(*target)
	if err != nil {
		fatalf("failed to create output file %s: %s", *target, err)
	}
	err = t.Execute(out, gen)
	if err != nil {
		fatalf("failed to execute template: %s", err)
	}
	fmt.Printf("%s: wrote RPC stubs for %s to %s\n", os.Args[0], *rpcType, *target)
	if out, err := exec.Command("go", "fmt", *target).CombinedOutput(); err != nil {
		fatalf("failed to run go fmt on %s: %s: %s", *target, err, string(out))
	}
}
Esempio n. 12
0
package movieinfo

import "github.com/alecthomas/template"

var tpl = template.Must(
	template.New("").
		Funcs(template.FuncMap{}).
		ParseGlob("templates/*.gohtml"),
)
Esempio n. 13
0
func main() {
	fmt.Printf("\n%v\n", "Starting..")

	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {

		w.Header().Add("Content Type", "text/html")

		myTemplate := template.New("Template")
		myTemplate.New("header").Parse(header)
		myTemplate.New("footer").Parse(footer)
		myTemplate.New("docForIteration").Parse(doc)

		things := Things{
			Title:   "Title of MyList",
			Details: []string{"A thing", "B thing", "C thing", "D thing"},
		}
		myTemplate.Lookup("docForIteration").Execute(w, things)

		/*
			if (err == nil) {
				context := struct {Name    string
								   SurName string
								   Url     string}{Name:"Eralp", SurName:"Erat", Url:req.URL.Path}
				temp.Execute(w, context)
			} else {
				w.Header().Add("Content Type", "text/plain")
				//w.WriteHeader(404)
				w.Write([]byte("Fantastic an error occured!"))
			}
		*/
	})

	go func() {
		fmt.Printf("\n%v", "Started!")
	}()

	http.ListenAndServe(":9002", nil)

	return

	// it's super simple built-in file server!
	http.ListenAndServe(":9001", http.FileServer(http.Dir("Public")))

	return

	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		path := "Public/" + req.URL.Path
		fmt.Printf("\nPATH : %v\n", path)

		//try to read each calling
		//data, err := ioutil.ReadFile(string(path))

		//for buffering
		data, err := os.Open(string(path))

		if err == nil {
			buffer := bufio.NewReader(data)
			contentType := "text/plain"
			if strings.HasSuffix(path, ".css") {
				contentType = "text/css"
			} else if strings.HasSuffix(path, ".html") {
				contentType = "text/html"
			} else if strings.HasSuffix(path, ".js") {
				contentType = "application/javascript"
			} else if strings.HasSuffix(path, ".png") {
				contentType = "image/png"
			} else if strings.HasSuffix(path, ".mp4") {
				contentType = "video/mp4"
			} else if strings.HasSuffix(path, ".pdf") {
				contentType = "application/pdf"
			}
			w.Header().Add(
				"Content Type", contentType,
			)
			//w.Write([]byte(data))
			buffer.WriteTo(w)
		} else {
			w.WriteHeader(404)
			w.Write([]byte("404 Error - Page Not Found!"))
		}
	})
	/*
		http.HandleFunc("/",new(MyHandler))
	*/
	http.ListenAndServe(":9001", nil)
}