示例#1
1
// list specific pod details
func GetPod(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	// node name from user.
	podName := vars["podName"]
	fmt.Fprint(w, string(podName))
	// to do need to read api and port of api server from configuration file
	// TODO: change namespace to flexible.
	var dat map[string]interface{}
	res, err := http.Get(thoth.KubeApi + "/api/v1/namespaces/default/pods/" + podName)
	if err != nil {
		panic(err)
	}
	body, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		panic(err)
	}
	if err := json.Unmarshal(body, &dat); err != nil {
		panic(err)
	}
	pretty_body, err := json.MarshalIndent(dat, "", "  ")
	if err != nil {
		panic(err)
	}
	fmt.Fprint(w, string(pretty_body))
}
示例#2
1
文件: tag.go 项目: src-d/go-git
// Encode transforms a Tag into a plumbing.EncodedObject.
func (t *Tag) Encode(o plumbing.EncodedObject) error {
	o.SetType(plumbing.TagObject)
	w, err := o.Writer()
	if err != nil {
		return err
	}
	defer ioutil.CheckClose(w, &err)

	if _, err = fmt.Fprintf(w,
		"object %s\ntype %s\ntag %s\ntagger ",
		t.Target.String(), t.TargetType.Bytes(), t.Name); err != nil {
		return err
	}

	if err = t.Tagger.Encode(w); err != nil {
		return err
	}

	if _, err = fmt.Fprint(w, "\n\n"); err != nil {
		return err
	}

	if _, err = fmt.Fprint(w, t.Message); err != nil {
		return err
	}

	return err
}
示例#3
1
// describeObjects prints out information about the objects of a template
func (d *TemplateDescriber) describeObjects(objects []runtime.Object, out *tabwriter.Writer) {
	formatString(out, "Objects", " ")
	indent := "    "
	for _, obj := range objects {
		if d.ObjectDescriber != nil {
			output, err := d.DescribeObject(obj)
			if err != nil {
				fmt.Fprintf(out, "error: %v\n", err)
				continue
			}
			fmt.Fprint(out, output)
			fmt.Fprint(out, "\n")
			continue
		}

		_, kind, _ := d.ObjectTyper.ObjectVersionAndKind(obj)
		meta := kapi.ObjectMeta{}
		meta.Name, _ = d.MetadataAccessor.Name(obj)
		fmt.Fprintf(out, fmt.Sprintf("%s%s\t%s\n", indent, kind, meta.Name))
		//meta.Annotations, _ = d.MetadataAccessor.Annotations(obj)
		//meta.Labels, _ = d.MetadataAccessor.Labels(obj)
		/*if len(meta.Labels) > 0 {
			formatString(out, indent+"Labels", formatLabels(meta.Labels))
		}
		formatAnnotations(out, meta, indent)*/
	}
}
示例#4
1
func newRow(w io.Writer, row string, first bool) {
	if !first {
		fmt.Fprint(w, "  </tr>\n")
	}
	fmt.Fprint(w, "  <tr>\n")
	fmt.Fprintf(w, "    <td>%s:</td>\n", row)
}
示例#5
1
// AddFileHandler adds the file path to the database. It should be usually be given to an POST endpoint
// with id as the parameter
// Ex: /file/:id
func AddFileHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	decoder := json.NewDecoder(r.Body)
	// TODO: ps is there for checking emptiness. Should be replaced
	var js, ps jsonStruct
	if err := decoder.Decode(&js); err != nil || js == ps {
		w.WriteHeader(400)
		return
	}

	couchServer, err := couchdb.NewClient("http://127.0.0.1:5984", nil)
	db, _ := couchServer.CreateDB("files")
	userID := memberlist.DefaultWANConfig().Name

	_, err = db.Put(p.ByName("id"), file{UUID: uuid.NewV4().String(), Fname: path.Base(js.Path), UserID: userID}, "")
	if err != nil {
		w.WriteHeader(500)
		fmt.Fprint(w, err)
		return
	}

	// TODO: Send 409 for conflict
	if err := AddFile(p.ByName("id"), js.Path); err != nil {
		w.WriteHeader(500)
		fmt.Fprint(w, err)
		return
	}

	w.WriteHeader(201)
}
示例#6
1
文件: socklog.go 项目: v-gu/mysqltc
func NewSocketLogWriter(proto, hostport string) SocketLogWriter {
	sock, err := net.Dial(proto, hostport)
	if err != nil {
		fmt.Fprintf(os.Stderr, "NewSocketLogWriter(%q): %s\n", hostport, err)
		return nil
	}

	w := SocketLogWriter(make(chan *LogRecord, LogBufferLength))

	go func() {
		defer func() {
			if sock != nil && proto == "tcp" {
				sock.Close()
			}
		}()

		for rec := range w {
			// Marshall into JSON
			js, err := json.Marshal(rec)
			if err != nil {
				fmt.Fprint(os.Stderr, "SocketLogWriter(%q): %s", hostport, err)
				return
			}

			_, err = sock.Write(js)
			if err != nil {
				fmt.Fprint(os.Stderr, "SocketLogWriter(%q): %s", hostport, err)
				return
			}
		}
	}()

	return w
}
示例#7
1
//line fitted_type.got:17
func drawFittedTableQLetters(rSeq, qSeq alphabet.QLetters, index alphabet.Index, table []int, a [][]int) {
	tw := tabwriter.NewWriter(os.Stdout, 0, 0, 0, ' ', tabwriter.AlignRight|tabwriter.Debug)
	fmt.Printf("rSeq: %s\n", rSeq)
	fmt.Printf("qSeq: %s\n", qSeq)
	fmt.Fprint(tw, "\tqSeq\t")
	for _, l := range qSeq {
		fmt.Fprintf(tw, "%c\t", l)
	}
	fmt.Fprintln(tw)

	r, c := rSeq.Len()+1, qSeq.Len()+1
	fmt.Fprint(tw, "rSeq\t")
	for i := 0; i < r; i++ {
		if i != 0 {
			fmt.Fprintf(tw, "%c\t", rSeq[i-1].L)
		}

		for j := 0; j < c; j++ {
			p := pointerFittedQLetters(rSeq, qSeq, i, j, table, index, a, c)
			if p != "" {
				fmt.Fprintf(tw, "%s % 3v\t", p, table[i*c+j])
			} else {
				fmt.Fprintf(tw, "%v\t", table[i*c+j])
			}
		}
		fmt.Fprintln(tw)
	}
	tw.Flush()
}
示例#8
0
func xml_txw4i(w http.ResponseWriter, r *http.Request) {
	if !ipchecker(r) {
		return
	}

	w.Header()["Content-Type"] = []string{"text/xml"}
	w.Write([]byte("<pending>"))
	network.TxMutex.Lock()
	for _, v := range network.WaitingForInputs {
		w.Write([]byte("<wait4>"))
		fmt.Fprint(w, "<id>", v.TxID.String(), "</id>")
		for x, t := range v.Ids {
			w.Write([]byte("<tx>"))
			if v, ok := network.TransactionsRejected[x]; ok {
				fmt.Fprint(w, "<id>", v.Id.String(), "</id>")
				fmt.Fprint(w, "<time>", t.Unix(), "</time>")
			} else {
				fmt.Fprint(w, "<id>FATAL ERROR!!! This should not happen! Please report</id>")
				fmt.Fprint(w, "<time>", time.Now().Unix(), "</time>")
			}
			w.Write([]byte("</tx>"))
		}
		w.Write([]byte("</wait4>"))
	}
	network.TxMutex.Unlock()
	w.Write([]byte("</pending>"))
}
示例#9
0
文件: render.go 项目: kierdavis/k12
func render(w io.Writer, l *layout.Layout, wires []*layout.Wire, fps map[string]*footprint.Footprint, flip bool) {
	minX := l.MinX - 1
	minY := l.MinY - 1
	maxX := l.MaxX + 1
	maxY := l.MaxY + 1

	innerWidth := maxX - minX
	innerHeight := maxY - minY

	outerHeight := 600
	outerWidth := (outerHeight * innerWidth) / innerHeight

	fmt.Fprint(w, "<?xml version='1.0' standalone='no'?>\n")
	fmt.Fprint(w, "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n")
	fmt.Fprintf(w, "<svg width='%d' height='%d' viewBox='%d %d %d %d' version='1.1' xmlns='http://www.w3.org/2000/svg'>\n", outerWidth, outerHeight, minX, minY, innerWidth, innerHeight)
	//fmt.Fprintf(w, "  <rect x='%d' y='%d' width='%d' height='%d' stroke='#999900' stroke-width='0.1' fill='none'/>\n", minX, minY, innerWidth, innerHeight)

	if flip {
		fmt.Fprintf(w, "<g transform='matrix(-1 0 0 1 %d 0)'>\n", innerWidth+minX*2)
	}

	renderGraphics(w, l)
	renderComponents(w, l, fps)
	renderWires(w, l, wires, fps)

	if flip {
		fmt.Fprint(w, "</g>\n")
	}

	fmt.Fprint(w, "</svg>\n")
}
示例#10
0
// 修改项目
// uri: /project/modify{json:(|.json)}
func ModifyProjectHandler(rw http.ResponseWriter, req *http.Request) {
	id := req.FormValue("id")
	if id == "" {
		util.Redirect(rw, req, "/projects")
		return
	}

	vars := mux.Vars(req)
	// 请求编辑项目页面
	if req.Method != "POST" || vars["json"] == "" {
		project := service.FindProject(id)
		req.Form.Set(filter.CONTENT_TPL_KEY, "/template/projects/new.html")
		filter.SetData(req, map[string]interface{}{"project": project, "activeProjects": "active"})
		return
	}

	user, _ := filter.CurrentUser(req)
	err := service.PublishProject(user, req.PostForm)
	if err != nil {
		if err == service.NotModifyAuthorityErr {
			rw.WriteHeader(http.StatusForbidden)
			return
		}
		fmt.Fprint(rw, `{"ok": 0, "error":"内部服务错误!"}`)
		return
	}
	fmt.Fprint(rw, `{"ok": 1, "data":""}`)
}
示例#11
0
文件: run.go 项目: db47h/ivy
// printValues neatly prints the values returned from execution, followed by a newline.
// It also handles the ')debug types' output.
// The return value reports whether it printed anything.
func printValues(conf *config.Config, writer io.Writer, values []value.Value) bool {
	if len(values) == 0 {
		return false
	}
	if conf.Debug("types") {
		for i, v := range values {
			if i > 0 {
				fmt.Fprint(writer, ",")
			}
			fmt.Fprintf(writer, "%T", v)
		}
		fmt.Fprintln(writer)
	}
	printed := false
	for _, v := range values {
		if _, ok := v.(parse.Assignment); ok {
			continue
		}
		s := v.Sprint(conf)
		if printed && len(s) > 0 && s[len(s)-1] != '\n' {
			fmt.Fprint(writer, " ")
		}
		fmt.Fprint(writer, s)
		printed = true
	}
	if printed {
		fmt.Fprintln(writer)
	}
	return printed
}
示例#12
0
func (s *metricFileSuite) TestContention(c *gc.C) {
	fileName := filepath.Join(s.spoolDir, "foo")
	mf1, err := createMetricFile(fileName)
	c.Assert(err, gc.IsNil)
	mf2, err := createMetricFile(fileName)
	c.Assert(err, gc.IsNil)

	_, err = fmt.Fprint(mf1, "emacs")
	c.Assert(err, gc.IsNil)
	_, err = fmt.Fprint(mf2, "vi")
	c.Assert(err, gc.IsNil)

	_, err = os.Stat(fileName)
	c.Assert(os.IsNotExist(err), jc.IsTrue)

	err = mf2.Close()
	c.Assert(err, gc.IsNil)
	err = mf1.Close()
	c.Assert(err, gc.NotNil)

	st, err := os.Stat(fileName)
	c.Assert(err, gc.IsNil)
	c.Assert(st.Size(), gc.Equals, int64(2))
	contents, err := ioutil.ReadFile(fileName)
	c.Assert(err, gc.IsNil)
	c.Assert(contents, gc.DeepEquals, []byte("vi"))
}
示例#13
0
func writeStruct(w io.Writer, val *reflect.StructValue) (err os.Error) {
	if _, err = fmt.Fprint(w, "{"); err != nil {
		return
	}

	typ := val.Type().(*reflect.StructType)

	for i := 0; i < val.NumField(); i++ {
		fieldValue := val.Field(i)
		if _, err = fmt.Fprintf(w, "%s:", Quote(typ.Field(i).Name)); err != nil {
			return
		}
		if err = writeValue(w, fieldValue); err != nil {
			return
		}
		if i < val.NumField()-1 {
			if _, err = fmt.Fprint(w, ","); err != nil {
				return
			}
		}
	}

	_, err = fmt.Fprint(w, "}")
	return
}
示例#14
0
func writeMap(w io.Writer, val *reflect.MapValue) (err os.Error) {
	key := val.Type().(*reflect.MapType).Key()
	if _, ok := key.(*reflect.StringType); !ok {
		return &MarshalError{val.Type()}
	}

	keys := val.Keys()
	if _, err = fmt.Fprint(w, "{"); err != nil {
		return
	}

	for i := 0; i < len(keys); i++ {
		if _, err = fmt.Fprintf(w, "%s:", Quote(keys[i].(*reflect.StringValue).Get())); err != nil {
			return
		}

		if err = writeValue(w, val.Elem(keys[i])); err != nil {
			return
		}

		if i < len(keys)-1 {
			if _, err = fmt.Fprint(w, ","); err != nil {
				return
			}
		}
	}

	_, err = fmt.Fprint(w, "}")
	return
}
func resourcePostgreSQLExtensionCreate(d *schema.ResourceData, meta interface{}) error {
	c := meta.(*Client)
	c.catalogLock.Lock()
	defer c.catalogLock.Unlock()

	conn, err := c.Connect()
	if err != nil {
		return err
	}
	defer conn.Close()

	extName := d.Get(extNameAttr).(string)

	b := bytes.NewBufferString("CREATE EXTENSION ")
	fmt.Fprint(b, pq.QuoteIdentifier(extName))

	if v, ok := d.GetOk(extSchemaAttr); ok {
		fmt.Fprint(b, " SCHEMA ", pq.QuoteIdentifier(v.(string)))
	}

	if v, ok := d.GetOk(extVersionAttr); ok {
		fmt.Fprint(b, " VERSION ", pq.QuoteIdentifier(v.(string)))
	}

	query := b.String()
	_, err = conn.Query(query)
	if err != nil {
		return errwrap.Wrapf("Error creating extension: {{err}}", err)
	}

	d.SetId(extName)

	return resourcePostgreSQLExtensionReadImpl(d, meta)
}
示例#16
0
// Format outputs a pretty-printed Const.
func (f Const) Format(out fmt.State, verb rune) {
	if f == true {
		fmt.Fprint(out, "true")
	} else {
		fmt.Fprint(out, "false")
	}
}
func CuePointsHandler(w http.ResponseWriter, r *http.Request, c *Config) {

	streamID, cuePointType, err := fetchParams(r)
	if err != nil {
		w.WriteHeader(400)
		fmt.Fprint(w, err)
		log.Println(err)
		return
	}

	cuePoint, timedMetadata, err := cuepoints.New(cuePointType, r)
	if err != nil {
		w.WriteHeader(400)
		fmt.Fprint(w, err)
		log.Println(err)
		return
	}

	stream, err := resolveStream(streamID, w, c)
	if err != nil {
		fmt.Fprint(w, err)
		log.Println(err)
		return
	}

	go injectCuePoint(stream, cuePoint, timedMetadata, c)

	w.WriteHeader(201)
	fmt.Fprint(w, stream.Name)
}
示例#18
0
文件: show_ref.go 项目: jbrukh/ggit
/*
TODO: remove this method, it is mainly for debugging
*/
func (b *ShowRefBuiltin) Which(p *Params) {
	repo := p.Repo.(*api.DiskRepository)
	fmtr := format.NewFormat(p.Wout)

	fmt.Fprintln(p.Wout, "Loose refs:")
	refs, e := repo.LooseRefs()
	if e != nil {
		fmt.Fprint(p.Werr, e.Error())
		return
	}
	for _, v := range refs {
		fmtr.Ref(v)
		fmtr.Lf()
	}

	fmt.Fprintln(p.Wout, "\nPacked refs:")
	prefs, e := repo.PackedRefs()
	if e != nil {
		fmt.Fprint(p.Werr, e.Error())
		return
	}
	for _, v := range prefs {
		fmtr.Ref(v)
		fmtr.Lf()
	}
}
示例#19
0
func handleRootHealthz(w http.ResponseWriter, r *http.Request) {
	lock.RLock()
	defer lock.RUnlock()
	failed := false
	var verboseOut bytes.Buffer
	for _, name := range names {
		check, found := checks[name]
		if !found {
			// this should not happen
			http.Error(w, fmt.Sprintf("Internal server error: check \"%q\" not registered", name), http.StatusInternalServerError)
			return
		}
		err := check.check(r)
		if err != nil {
			fmt.Fprintf(&verboseOut, "[-]%v failed: %v\n", check.name, err)
			failed = true
		} else {
			fmt.Fprintf(&verboseOut, "[+]%v ok\n", check.name)
		}
	}
	// always be verbose on failure
	if failed {
		http.Error(w, fmt.Sprintf("%vhealthz check failed", verboseOut.String()), http.StatusInternalServerError)
		return
	}

	if _, found := r.URL.Query()["verbose"]; !found {
		fmt.Fprint(w, "ok")
		return
	} else {
		verboseOut.WriteTo(w)
		fmt.Fprint(w, "healthz check passed\n")
	}
}
示例#20
0
文件: prolix.go 项目: gaal/prolix-go
func importSnippet(subsitutions []string) (ok bool) {
	for _, sub := range subsitutions {
		if len(sub) < 4 {
			fmt.Fprintf(os.Stderr, "invalid substitution: %q\n", sub)
			return
		}
		delim := sub[1:2]
		// TODO(gaal): paired delimiters, e.g., s{foo}{bar}
		parse := regexp.MustCompile("^s" + delim +
			`((?:\\.|[^` + regexp.QuoteMeta(delim) + `])*)` + delim +
			`((?:\\.|[^` + regexp.QuoteMeta(delim) + `])*)` + delim + "([ig])*$")
		parsedSub := parse.FindStringSubmatch(sub)
		if len(parsedSub) != 4 {
			fmt.Fprint(os.Stderr, "invalid substitution: ", sub)
			return
		}
		global := strings.Contains(parsedSub[3], "g")
		ignoreCase := strings.Contains(parsedSub[3], "i")
		pat := parsedSub[1]
		if ignoreCase {
			pat = "(?i)" + pat
		}
		if search, err := regexp.Compile(pat); err == nil {
			substitutionVals = append(substitutionVals, Substitution{search, parsedSub[2], global})
		} else {
			fmt.Fprint(os.Stderr, "invalid substitution: ", sub)
			return
		}
	}
	return true
}
示例#21
0
func (d AsyncGofunge93Debugger) Debug(ip IP) {
	inst := d.AsyncGofunge93.code[ip.Dim(1)][ip.Dim(0)];
	if d.printCoords {
		fmt.Fprintf(os.Stderr, "\n%c (%v, %v)", inst, ip.Dim(0), ip.Dim(1));
	}
	if d.printStack {
		fmt.Fprintf(os.Stderr, "\n%v", d.AsyncGofunge93.stack.v.Data());
	}
	if d.printTrace {
		fmt.Fprint(os.Stderr, "\n");
		for i, row := range d.AsyncGofunge93.code {
			if int32(i) == ip.Dim(1) {
				fmt.Fprint(os.Stderr, string(row[0:ip.Dim(0)]));
				fmt.Fprint(os.Stderr, "█");
				fmt.Fprintln(os.Stderr, string(row[ip.Dim(0)+1:len(row)]));
			}
			else {
				fmt.Fprintln(os.Stderr, string(row));
			}
		}
	}
	if d.pause {
		os.Stdin.Read(make([]byte, 1));
	}
}
示例#22
0
文件: fs2s3.go 项目: reedobrien/wpgo
func shouldUpdate(resp *http.Response, fi os.FileInfo, newer, newermetamtime bool) bool {
	var stale bool = false
	filemtime := fi.ModTime()
	if newermetamtime {
		parsed, err := time.Parse(time.RFC1123, resp.Header.Get("x-amz-meta-last-modified"))
		if err != nil {
			// can't see metamtime upload anyhow
			stale = true
			fmt.Fprint(os.Stderr, "Can't read metamtime, setting stale to upload again\n")
		}
		if parsed.Before(filemtime) {
			stale = true
		}
	}
	if newer {
		parsed, err := time.Parse(time.RFC1123, resp.Header.Get("Last-Modified"))
		if err != nil {
			// can't see metamtime upload anyhow
			stale = true
			fmt.Fprint(os.Stderr, "Can't read metamtime, setting stale to upload again\n")
		}
		if parsed.Before(filemtime) {
			stale = true
		}
	}
	return stale
}
示例#23
0
func loadPkgIndex() {
	pkgIndex.Lock()
	pkgIndex.m = make(map[string][]pkg)
	pkgIndex.Unlock()

	var wg sync.WaitGroup
	for _, path := range build.Default.SrcDirs() {
		f, err := os.Open(path)
		if err != nil {
			fmt.Fprint(os.Stderr, err)
			continue
		}
		children, err := f.Readdir(-1)
		f.Close()
		if err != nil {
			fmt.Fprint(os.Stderr, err)
			continue
		}
		for _, child := range children {
			if child.IsDir() {
				wg.Add(1)
				go func(path, name string) {
					defer wg.Done()
					loadPkg(&wg, path, name)
				}(path, child.Name())
			}
		}
	}
	wg.Wait()
}
示例#24
0
func PrintUnassignedWarning(writer io.Writer, commits []*git.Commit) (n int64, err error) {
	var output bytes.Buffer

	// Let's be colorful!
	redBold := color.New(color.FgRed).Add(color.Bold).SprintFunc()
	fmt.Fprint(&output,
		redBold("Warning: There are some commits missing the Story-Id tag.\n"))

	red := color.New(color.FgRed).SprintFunc()
	fmt.Fprint(&output,
		red("Make sure that this is alright before proceeding further.\n\n"))

	hashRe := regexp.MustCompile("^[0-9a-f]{40}$")

	yellow := color.New(color.FgYellow).SprintFunc()

	for _, commit := range commits {
		var (
			sha    = commit.SHA
			source = commit.Source
			title  = prompt.ShortenCommitTitle(commit.MessageTitle)
		)
		if hashRe.MatchString(commit.Source) {
			source = "unknown commit source branch"
		}

		fmt.Fprintf(&output, "  %v | %v | %v\n", yellow(sha), yellow(source), title)
	}

	// Write the output to the writer.
	return io.Copy(ansicolor.NewAnsiColorWriter(writer), &output)
}
示例#25
0
func (*changePasswordCommand) generateOrReadPassword(ctx *cmd.Context, generate bool) (string, error) {
	if generate {
		password, err := utils.RandomPassword()
		if err != nil {
			return "", errors.Annotate(err, "failed to generate random password")
		}
		randomPasswordNotify(password)
		return password, nil
	}

	// Don't add the carriage returns before readPassword, but add
	// them directly after the readPassword so any errors are output
	// on their own lines.
	fmt.Fprint(ctx.Stdout, "password: "******"\n")
	if err != nil {
		return "", errors.Trace(err)
	}
	fmt.Fprint(ctx.Stdout, "type password again: ")
	verify, err := readPassword()
	fmt.Fprint(ctx.Stdout, "\n")
	if err != nil {
		return "", errors.Trace(err)
	}
	if password != verify {
		return "", errors.New("Passwords do not match")
	}
	return password, nil
}
示例#26
0
文件: config.go 项目: ChrisKun/pythia
// UsageError prints msg using fmt.Fprint, followed by the usage notice, and
// exits with error UsageExitStatus.
func UsageError(msg ...interface{}) {
	fmt.Fprint(os.Stderr, os.Args[0], ": ")
	fmt.Fprint(os.Stderr, msg...)
	fmt.Fprint(os.Stderr, "\n")
	Usage()
	os.Exit(UsageExitStatus)
}
示例#27
0
func writeViolatingResourceData(minCPU, maxCPU, baselineMinCPU, baselineMaxCPU, allowedVariance float64, enableOutputColoring bool, writer *tabwriter.Writer) {
	fmt.Fprint(writer, "(")
	changeColorFloat64AndWrite(minCPU, baselineMinCPU, allowedVariance, enableOutputColoring, writer)
	fmt.Fprint(writer, ",")
	changeColorFloat64AndWrite(maxCPU, baselineMaxCPU, allowedVariance, enableOutputColoring, writer)
	fmt.Fprint(writer, ")")
}
示例#28
0
func refreshFromSource() {
	certData := bytes.NewBuffer([]byte{})

	bo := backoff.NewExponentialBackOff()
	bo.MaxElapsedTime = time.Minute

	err := backoff.Retry(func() error {
		src, err := http.Get(certDataSource)
		if err != nil {
			return err
		}
		defer src.Body.Close()

		license, cvsID, objects := cert.ParseInput(src.Body)

		fmt.Fprint(certData, license)
		if len(cvsID) > 0 {
			fmt.Fprint(certData, "CVS_ID "+cvsID+"\n")
		}

		cert.OutputTrustedCerts(certData, objects)

		return nil
	}, bo)

	if err != nil {
		log.Fatal(err)
	}

	saveToCache(strconv.FormatInt(time.Now().UTC().Unix(), 10), certData.Bytes())
	latestCertificates = certData.Bytes()
}
示例#29
0
func main() {
	file, err := os.Create("schema.pqt.go")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	// For simplicity it is going to be empty.
	sch := schema("example")
	fmt.Fprint(file, `
        // Code generated by pqt.
        // source: cmd/appg/main.go
        // DO NOT EDIT!
    `)
	err = pqtgo.NewGenerator().
		SetPostgresVersion(9.5).
		SetAcronyms(acronyms).
		SetVisibility(pqtgo.Private).
		GenerateTo(sch, file)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Fprint(file, "/// SQL ...\n")
	fmt.Fprint(file, "const SQL = `\n")
	if err := pqtsql.NewGenerator().GenerateTo(sch, file); err != nil {
		log.Fatal(err)
	}
	fmt.Fprint(file, "`")
}
示例#30
0
func handleRegisterApp(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	uuid, err := types.NewUUID(mux.Vars(r)["uuid"])
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "UUID is missing or malformed: %v", err)
		return
	}

	an := mux.Vars(r)["app"]
	if an == "" {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprint(w, "app missing")
		return
	}

	im := &schema.ImageManifest{}
	if err := json.NewDecoder(r.Body).Decode(im); err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "JSON-decoding failed: %v", err)
		return
	}

	err = pods.addApp(uuid, an, im)
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprint(w, "Pod with given UUID not found")
		return
	}

	w.WriteHeader(http.StatusOK)
}