示例#1
0
func (t *Test) printDebugOnfail() {
	if t.failed && t.PrintDebugOnFail {
		fmt.Println("\033[1;36mDEBUG REQUEST\033[0m")
		// request
		fmt.Printf("  \033[1;33mURL\033[0m: %s\n", t.Request.URL.String())
		fmt.Printf("  \033[1;33mHeaders\033[0m: %+v\n", t.request.Header)
		fmt.Printf("  \033[1;33mBody\033[0m: ")
		if t.Request.BodyString != "" {
			fmt.Println(t.Request.BodyString)
		} else if t.Request.BodyJson != nil {
			b, err := json.Marshal(t.Request.BodyJson)
			if err != nil {
				t.fail(err)
				return
			}
			if t.PrintJsonIndented {
				var out bytes.Buffer
				if err = json.Indent(&out, b, "\t", "  "); err != nil {
					fmt.Println(err)
				} else {
					fmt.Println(out.String())
				}
			} else {
				fmt.Printf("%s\n", b)
			}
		} else {
			fmt.Println("")
		}
		//response
		if t.Response != nil {
			fmt.Println("\033[1;36mDEBUG RESPONSE\033[0m")
			if t.response != nil {
				fmt.Printf("  \033[1;33mHeaders\033[0m: %+v\n", t.response.Header)
				fmt.Printf("  \033[1;33mStatus code\033[0m: %+v\n", t.response.StatusCode)
				fmt.Printf("  \033[1;33mStatus\033[0m: %+v\n", t.response.Status)
				if t.Response.body != nil {
					defaultBodyPrint := false
					fmt.Printf("  \033[1;33mBody\033[0m: ")
					if strings.Contains(strings.ToLower(t.Response.contentType), "application/json") {
						if t.PrintJsonIndented {
							var out bytes.Buffer
							if err := json.Indent(&out, t.Response.body, "\t", "  "); err != nil {
								fmt.Println(err)
							} else {
								fmt.Println(out.String())
							}
						} else {
							defaultBodyPrint = true
						}
					}
					if defaultBodyPrint {
						fmt.Printf("%s\n", t.Response.body)
					}
				}
			} else {
				fmt.Println("  \033[0;31mno response\033[0m")
			}
		}
	}
}
示例#2
0
文件: tst.go 项目: ustrajunior/minion
func AssertJSONBody(tb testing.TB, exp, act interface{}) {
	red := ansi.ColorCode("red+h:black")
	green := ansi.ColorCode("green+h:black")
	yellow := ansi.ColorFunc("yellow+h")
	reset := ansi.ColorCode("reset")

	var actBuf bytes.Buffer
	err := json.Indent(&actBuf, []byte(act.(string)), "", " ")
	if err != nil {
		fmt.Println(red, "Invalid json: ", act, reset)
	}
	act = string(actBuf.Bytes())

	var expBuf bytes.Buffer
	err = json.Indent(&expBuf, []byte(exp.(string)), "", " ")
	if err != nil {
		fmt.Println(red, "Invalid json: ", exp, reset)
	}
	exp = string(expBuf.Bytes())

	if !reflect.DeepEqual(exp, act) {
		_, file, line, _ := runtime.Caller(1)

		fmt.Println(yellow(fmt.Sprintf("%s:%d", filepath.Base(file), line)))
		fmt.Println(green, "Expected: ", exp, reset)
		fmt.Println(red, "     Got: ", act, reset)

		tb.FailNow()
	}
}
示例#3
0
func MatchJSON(actual, want interface{}) (success bool, message string, err error) {
	actualString, aok := toString(actual)
	expectedString, eok := toString(want)

	if aok && eok {
		abuf := new(bytes.Buffer)
		ebuf := new(bytes.Buffer)

		if err := json.Indent(abuf, []byte(actualString), "", "  "); err != nil {
			return false, "", err
		}

		if err := json.Indent(ebuf, []byte(expectedString), "", "  "); err != nil {
			return false, "", err
		}

		var aval interface{}
		var eval interface{}

		json.Unmarshal([]byte(actualString), &aval)
		json.Unmarshal([]byte(expectedString), &eval)

		if reflect.DeepEqual(aval, eval) {
			return true, fmt.Sprintf("%s not to match JSON of %s", abuf.String(), ebuf.String()), nil
		} else {
			return false, fmt.Sprintf("%s  to match JSON of %s", abuf.String(), ebuf.String()), nil
		}
	} else {
		return false, "", fmt.Errorf("MatchJSONMatcher matcher requires a string or stringer.  Got:\n%#v", actual)
	}
	return false, "", nil
}
示例#4
0
func (matcher *MatchJSONMatcher) Match(actual interface{}) (success bool, message string, err error) {
	actualString, aok := toString(actual)
	expectedString, eok := toString(matcher.JSONToMatch)

	if aok && eok {
		abuf := new(bytes.Buffer)
		ebuf := new(bytes.Buffer)

		if err := json.Indent(abuf, []byte(actualString), "", "  "); err != nil {
			return false, "", err
		}

		if err := json.Indent(ebuf, []byte(expectedString), "", "  "); err != nil {
			return false, "", err
		}

		var aval interface{}
		var eval interface{}

		json.Unmarshal([]byte(actualString), &aval)
		json.Unmarshal([]byte(expectedString), &eval)

		if reflect.DeepEqual(aval, eval) {
			return true, format.Message(abuf.String(), "not to match JSON of", ebuf.String()), nil
		} else {
			return false, format.Message(abuf.String(), "to match JSON of", ebuf.String()), nil
		}
	} else {
		return false, "", fmt.Errorf("MatchJSONMatcher matcher requires a string or stringer.  Got:\n%s", format.Object(actual, 1))
	}
	return false, "", nil
}
示例#5
0
func (a *assertionGroup) ContainsJSON(s interface{}) *assertionGroup {
	js, err := json.Marshal(s)

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

	var expected bytes.Buffer
	err = json.Indent(&expected, js, "", "\t")

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

	var actual bytes.Buffer
	err = json.Indent(&actual, a.response.BodyBytes, "", "\t")

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

	if string(actual.Bytes()[:]) != string(expected.Bytes()[:]) {
		msg := fmt.Sprintf(`JSON body does not match:
%s
expected:
%s`, string(actual.Bytes()[:]), string(expected.Bytes()[:]))
		a.Errorf(msg)
	}

	return a
}
示例#6
0
func processJson(filename string, src []byte, opt *JsonFmtOption) ([]byte, error) {
	if opt.Compact {
		var out bytes.Buffer
		err := json.Compact(&out, src)
		if err != nil {
			return nil, err
		}
		return out.Bytes(), nil
	} else {
		var out bytes.Buffer
		var err error
		if opt.IndentTab {
			err = json.Indent(&out, src, "", "\t")
		} else {
			var indent string
			for i := 0; i < opt.TabWidth; i++ {
				indent += " "
			}
			err = json.Indent(&out, src, "", indent)
		}
		if err != nil {
			return nil, err
		}
		return out.Bytes(), nil
	}
	return src, nil
}
示例#7
0
func (srv *Server) CmdInspect(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
	cmd := rcli.Subcmd(stdout, "inspect", "CONTAINER", "Return low-level information on a container")
	if err := cmd.Parse(args); err != nil {
		return nil
	}
	if cmd.NArg() < 1 {
		cmd.Usage()
		return nil
	}
	name := cmd.Arg(0)
	var obj interface{}
	if container := srv.runtime.Get(name); container != nil {
		obj = container
	} else if image, err := srv.runtime.repositories.LookupImage(name); err == nil && image != nil {
		obj = image
	} else {
		// No output means the object does not exist
		// (easier to script since stdout and stderr are not differentiated atm)
		return nil
	}
	data, err := json.Marshal(obj)
	if err != nil {
		return err
	}
	indented := new(bytes.Buffer)
	if err = json.Indent(indented, data, "", "    "); err != nil {
		return err
	}
	if _, err := io.Copy(stdout, indented); err != nil {
		return err
	}
	stdout.Write([]byte{'\n'})
	return nil
}
示例#8
0
func dumpRaw(l logger.Logger, conf *config.Config) {
	storeAdapter, _ := connectToStoreAdapter(l, conf)
	fmt.Printf("Raw Dump - Current timestamp %d\n", time.Now().Unix())

	entries := sort.StringSlice{}

	node, err := storeAdapter.ListRecursively("/hm")
	if err != nil {
		panic(err)
	}
	walk(node, func(node storeadapter.StoreNode) {
		ttl := fmt.Sprintf("[TTL:%ds]", node.TTL)
		if node.TTL == 0 {
			ttl = "[TTL: ∞]"
		}
		buf := &bytes.Buffer{}
		err := json.Indent(buf, node.Value, "    ", "  ")
		value := buf.String()
		if err != nil {
			value = string(node.Value)
		}
		entries = append(entries, fmt.Sprintf("%s %s:\n    %s", node.Key, ttl, value))
	})

	sort.Sort(entries)
	for _, entry := range entries {
		fmt.Printf(entry + "\n")
	}
}
示例#9
0
func assertAst(t *testing.T, root ast.Node, case_name string) {
	var out []byte
	var err error
	if out, err = json.Marshal(root); err != nil {
		t.Fatal(err)
	}

	var buf bytes.Buffer
	if err = json.Indent(&buf, out, "", "\t"); err != nil {
		t.Fatal(err)
	}

	var file *os.File
	jsn := buf.String()
	if file, err = os.Open(kTestingPrefix + case_name + ".json"); err != nil {
		t.Logf("[%s] not found: %v, now dump: \n%s", case_name, err, jsn)
		if file, err = os.Create(kTestingPrefix + case_name + ".json_"); err != nil {
			panic(err)
		}
		file.Write(buf.Bytes())
		file.Close()
		return
	}
	defer file.Close()

	buf.Reset()
	if _, err = buf.ReadFrom(file); err != nil {
		t.Fatal(err)
	}
	if buf.String() != jsn {
		t.Fatalf("[%s] Assert failed, Expected: ----------\n%s\nValue is: ----------\n%s",
			case_name, buf.String(), jsn)
	}
}
示例#10
0
func main() {
	if len(os.Args) < 2 {
		fmt.Printf("Usage: %s file.ffindex\n", os.Args[0])
		return
	}

	f, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatalf("Can't open %s.", os.Args[1])
	}
	defer f.Close()

	idx, err := ffmsindex.ReadIndex(f)
	if err != nil {
		log.Fatalf(err.Error())
	}

	out, err := json.Marshal(idx)
	if err != nil {
		log.Fatalf(err.Error())
	}

	var b bytes.Buffer
	err = json.Indent(&b, out, "", "    ")
	if err != nil {
		log.Fatalf(err.Error())
	}

	b.WriteTo(os.Stdout)
}
示例#11
0
文件: commands.go 项目: jweede/docker
func (cli *DockerCli) CmdInspect(args ...string) error {
	cmd := Subcmd("inspect", "CONTAINER|IMAGE", "Return low-level information on a container/image")
	if err := cmd.Parse(args); err != nil {
		return nil
	}
	if cmd.NArg() != 1 {
		cmd.Usage()
		return nil
	}
	obj, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
	if err != nil {
		obj, _, err = cli.call("GET", "/images/"+cmd.Arg(0)+"/json", nil)
		if err != nil {
			return err
		}
	}

	indented := new(bytes.Buffer)
	if err = json.Indent(indented, obj, "", "    "); err != nil {
		return err
	}
	if _, err := io.Copy(os.Stdout, indented); err != nil {
		return err
	}
	return nil
}
示例#12
0
文件: main.go 项目: aclisp/kubecon
func editReplicationController(c *gin.Context) {
	namespace := c.Param("ns")
	rcname := c.Param("rc")
	_, delete := c.GetQuery("delete")

	rc, err := kubeclient.Get().ReplicationControllers(namespace).Get(rcname)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
		return
	}

	b, err := json.Marshal(rc)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
		return
	}

	var out bytes.Buffer
	err = json.Indent(&out, b, "", "  ")
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
		return
	}

	c.HTML(http.StatusOK, "replicationControllerEdit", gin.H{
		"title":     rcname,
		"namespace": namespace,
		"objname":   rcname,
		"json":      out.String(),
		"delete":    strconv.FormatBool(delete),
	})
}
示例#13
0
func (p *PactFileWriter) Write() error {
	if _, err := os.Stat(p.pactPath); os.IsNotExist(err) {
		os.MkdirAll(p.pactPath, 0777)
	}

	filename := path.Join(p.pactPath, p.pact.FileName())

	data, err := p.pact.ToJson()

	if err != nil {
		return err
	}

	//indent
	var out bytes.Buffer
	if err := json.Indent(&out, data, "", "\t"); err != nil {
		return err
	}

	if err := ioutil.WriteFile(filename, out.Bytes(), 0777); err != nil {
		return err
	}

	return nil
}
示例#14
0
func main() {
	args := flag.Args()
	if len(args) < 1 {
		lerr.Fatal("Prettifies json")
	}
	filename := args[0]

	unformattedJson, err := ioutil.ReadFile(filename)
	if err != nil {
		lerr.Fatal(err)
	}

	var out bytes.Buffer
	err = json.Indent(&out, unformattedJson, "", "  ")
	if err != nil {
		lerr.Fatal(err)
	}

	if write {
		ioutil.WriteFile(filename, out.Bytes(), 0777)
	} else {
		out.WriteTo(os.Stdout)
	}

}
示例#15
0
文件: main.go 项目: aclisp/kubecon
func editNode(c *gin.Context) {
	nodename := c.Param("no")
	_, delete := c.GetQuery("delete")

	node, err := kubeclient.Get().Nodes().Get(nodename)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
		return
	}

	b, err := json.Marshal(node)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
		return
	}

	var out bytes.Buffer
	err = json.Indent(&out, b, "", "  ")
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
		return
	}

	c.HTML(http.StatusOK, "nodeEdit", gin.H{
		"title":   nodename,
		"objname": nodename,
		"json":    out.String(),
		"delete":  strconv.FormatBool(delete),
	})
}
func getUser(token string) (bytes.Buffer, error) {
	target, _ := apiUrl.Parse(mePath)
	request := &http.Request{
		URL:    target,
		Method: "GET",
		Header: map[string][]string{
			"Accept":        []string{"application/json"},
			"Authorization": []string{fmt.Sprintf("bearer %s", token)},
		},
	}
	resp, err := http.DefaultClient.Do(request)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, errors.New("bad status " + resp.Status)
	}

	var prettyJSON bytes.Buffer
	error := json.Indent(&prettyJSON, resp.Body, "", "\t")

	/*
	   user := &User{}
	   dec := json.NewDecoder(resp.Body)
	   return user, dec.Decode(user)
	*/
}
示例#17
0
func (c *JsonRPCClient) TemplateExport(dirPath, format string, templates ...ZabbixTemplate) error {
	for _, v := range templates {
		var res JsonRPCResponseGeneral

		data := map[string]interface{}{
			"options": map[string][]string{"templates": []string{v.TemplateID}},
			"format":  format,
		}

		err := c.request(MethodConfigurationExport, data, &res)
		if err != nil {
			return err
		}

		fullPath := filepath.Join(dirPath, fmt.Sprintf("%s.%s", v.Name, format))
		fout, err := os.Create(fullPath)
		if err != nil {
			return err
		}
		defer fout.Close()

		var prettyJSON bytes.Buffer
		err = json.Indent(&prettyJSON, []byte(res.Result), "", "    ")
		if err != nil {
			return err
		}

		fout.WriteString(string(prettyJSON.Bytes()))
		fmt.Printf("Exported %+v\n", fullPath)
	}
	return nil
}
示例#18
0
func (h *Hoverfly) ExportSimulation() ([]byte, error) {
	slingRequest, err := h.buildGetRequest(v2ApiSimulation)
	if err != nil {
		return nil, err
	}

	response, err := h.doRequest(slingRequest)
	if err != nil {
		return nil, err
	}

	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Debug(err.Error())
		return nil, errors.New("Could not export from Hoverfly")
	}

	var jsonBytes bytes.Buffer
	err = json.Indent(&jsonBytes, body, "", "\t")
	if err != nil {
		log.Debug(err.Error())
		return nil, errors.New("Could not export from Hoverfly")
	}

	return jsonBytes.Bytes(), nil
}
示例#19
0
func (cli *DockerCli) CmdInspect(args ...string) error {
	cmd := Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container/image")
	if err := cmd.Parse(args); err != nil {
		return nil
	}
	if cmd.NArg() < 1 {
		cmd.Usage()
		return nil
	}
	fmt.Fprintf(cli.out, "[")
	for i, name := range args {
		if i > 0 {
			fmt.Fprintf(cli.out, ",")
		}
		obj, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
		if err != nil {
			obj, _, err = cli.call("GET", "/images/"+name+"/json", nil)
			if err != nil {
				fmt.Fprintf(cli.err, "%s\n", err)
				continue
			}
		}

		indented := new(bytes.Buffer)
		if err = json.Indent(indented, obj, "", "    "); err != nil {
			fmt.Fprintf(cli.err, "%s\n", err)
			continue
		}
		if _, err := io.Copy(cli.out, indented); err != nil {
			fmt.Fprintf(cli.err, "%s\n", err)
		}
	}
	fmt.Fprintf(cli.out, "]")
	return nil
}
示例#20
0
func ExampleIndent() {
	type Road struct {
		Name   string
		Number int
	}
	roads := []Road{
		{"Diamond Fork", 29},
		{"Sheep Creek", 51},
	}

	b, err := json.Marshal(roads)
	if err != nil {
		log.Fatal(err)
	}

	var out bytes.Buffer
	json.Indent(&out, b, "=", "\t")
	out.WriteTo(os.Stdout)
	// Output:
	// [
	// =	{
	// =		"Name": "Diamond Fork",
	// =		"Number": 29
	// =	},
	// =	{
	// =		"Name": "Sheep Creek",
	// =		"Number": 51
	// =	}
	// =]
}
示例#21
0
func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) {
	var files []*plugin.CodeGeneratorResponse_File
	for _, file := range targets {
		glog.V(1).Infof("Processing %s", file.GetName())
		code, err := applyTemplate(param{File: file, reg: g.reg})
		if err == errNoTargetService {
			glog.V(1).Infof("%s: %v", file.GetName(), err)
			continue
		}
		if err != nil {
			return nil, err
		}

		var formatted bytes.Buffer
		json.Indent(&formatted, []byte(code), "", "  ")

		name := file.GetName()
		ext := filepath.Ext(name)
		base := strings.TrimSuffix(name, ext)
		output := fmt.Sprintf("%s.swagger.json", base)
		files = append(files, &plugin.CodeGeneratorResponse_File{
			Name:    proto.String(output),
			Content: proto.String(formatted.String()),
		})
		glog.V(1).Infof("Will emit %s", output)
	}
	return files, nil
}
示例#22
0
文件: config.go 项目: ineiti/prifi
func (hc *HostConfig) String() string {
	b := bytes.NewBuffer([]byte{})

	// write the hosts
	b.WriteString("{\"hosts\": [")
	for i, sn := range hc.SNodes {
		if i != 0 {
			b.WriteString(", ")
		}
		b.WriteString("\"" + sn.Name() + "\"")
	}
	b.WriteString("],")

	// write the tree structure
	b.WriteString("\"tree\": ")
	if len(hc.SNodes) != 0 {
		root := hc.SNodes[0]
		writeHC(b, hc, root)
	} else {
		b.WriteString("{}")
	}
	b.WriteString("}\n")

	// format the resulting JSON for readability
	bformatted := bytes.NewBuffer([]byte{})
	err := json.Indent(bformatted, b.Bytes(), "", "\t")
	if err != nil {
		fmt.Println(string(b.Bytes()))
		fmt.Println("ERROR: ", err)
	}

	return string(bformatted.Bytes())
}
示例#23
0
文件: main.go 项目: aclisp/kubecon
func editEndpoints(c *gin.Context) {
	namespace := c.Param("ns")
	epname := c.Param("ep")
	_, delete := c.GetQuery("delete")

	ep, err := kubeclient.Get().Endpoints(namespace).Get(epname)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
		return
	}

	b, err := json.Marshal(ep)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
		return
	}

	var out bytes.Buffer
	err = json.Indent(&out, b, "", "  ")
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error", gin.H{"error": err.Error()})
		return
	}

	c.HTML(http.StatusOK, "endpointsEdit", gin.H{
		"title":     epname,
		"namespace": namespace,
		"objname":   epname,
		"json":      out.String(),
		"delete":    strconv.FormatBool(delete),
	})
}
示例#24
0
文件: save.go 项目: niiyz/JapanGeoGo
func Save(path string, fts []Feature) {

	// Create FeatureCollection
	var fc = FeatureCollection{"FeatureCollection", fts}
	// Convert Struct To Json
	b, err := json.Marshal(&fc)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	var out bytes.Buffer
	json.Indent(&out, b, "    ", "    ")

	// Create New File
	file, err := os.Create(path)

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// File Close
	defer file.Close()

	// Wraite Bytes
	_, err = file.Write(b)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
示例#25
0
func pp(resp *http.Response, err error) (*http.Response, error) {
	if err != nil {
		return resp, err
	}
	log.Println(resp.Status)

	defer resp.Body.Close()
	src, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return resp, err
	}

	index := strings.Index(resp.Header.Get("Content-Type"), "json")

	if index > 0 {
		var b bytes.Buffer
		err := json.Indent(&b, src, "", "    ")
		if err != nil {
			return resp, err
		}
		fmt.Println(b.String())
	} else {
		fmt.Println(string(src))
	}
	return resp, err
}
示例#26
0
文件: main.go 项目: rollcat/json
func json_dump(o any) {
	b, err := json.Marshal(o)
	assert(err)
	var out bytes.Buffer
	json.Indent(&out, b, "", "\t")
	out.WriteTo(os.Stdout)
}
示例#27
0
// Writes an object to the response in JSON format.
func (h *handler) writeJSONStatus(status int, value interface{}) {
	if !h.requestAccepts("application/json") {
		log.Printf("WARNING: Client won't accept JSON, only %s", h.rq.Header.Get("Accept"))
		h.writeStatus(http.StatusNotAcceptable, "only application/json available")
		return
	}

	jsonOut, err := json.Marshal(value)
	if err != nil {
		log.Printf("WARNING: Couldn't serialize JSON for %v", value)
		h.writeStatus(http.StatusInternalServerError, "JSON serialization failed")
		return
	}
	if PrettyPrint {
		var buffer bytes.Buffer
		json.Indent(&buffer, jsonOut, "", "  ")
		jsonOut = append(buffer.Bytes(), '\n')
	}
	h.setHeader("Content-Type", "application/json")
	if h.rq.Method != "HEAD" {
		h.setHeader("Content-Length", fmt.Sprintf("%d", len(jsonOut)))
		if status > 0 {
			h.response.WriteHeader(status)
			h.logStatus(status, "")
		}
		h.response.Write(jsonOut)
	} else if status > 0 {
		h.response.WriteHeader(status)
		h.logStatus(status, "")
	}
}
示例#28
0
func SaveBuildGeneralDetails(buildName, buildNumber string) error {
	path, err := GetBuildDir(buildName, buildNumber)
	if err != nil {
		return err
	}
	path += BUILD_INFO_DETAILS
	var exists bool
	exists, err = ioutils.IsFileExists(path)
	if err != nil {
		return err
	}
	if exists {
		return nil
	}
	meta := BuildGeneralDetails{
		Timestamp: time.Now(),
	}
	b, err := json.Marshal(&meta)
	err = cliutils.CheckError(err)
	var content bytes.Buffer
	err = json.Indent(&content, b, "", "  ")
	err = cliutils.CheckError(err)
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(path, []byte(content.String()), 0600)
	return err
}
示例#29
0
func (f *File) Save() (err error) {
	var done sync.Mutex
	done.Lock()
	f.cbs <- func() {
		defer done.Unlock()
		tmpPath := f.path + "." + strconv.FormatInt(rand.Int63(), 10)
		var tmpF *os.File
		tmpF, err = os.Create(tmpPath)
		if err != nil {
			return
		}
		defer tmpF.Close()
		buf := new(bytes.Buffer)
		err = json.NewEncoder(buf).Encode(f.Obj)
		if err != nil {
			return
		}
		// indent
		indentBuf := new(bytes.Buffer)
		err = json.Indent(indentBuf, buf.Bytes(), "", "    ")
		if err != nil {
			return
		}
		_, err = tmpF.Write(indentBuf.Bytes())
		if err != nil {
			return
		}
		err = os.Rename(tmpPath, f.path)
		if err != nil {
			return
		}
	}
	done.Lock()
	return
}
示例#30
0
func main() {
	cbServ := flag.String("couchbase", "http://localhost:8091/",
		"URL to couchbase")
	cbBucket := flag.String("bucket", "default", "couchbase bucket")
	objName := flag.String("objname", "designDoc",
		"Name of the variable to create")
	flag.Parse()

	ddocName := flag.Arg(0)
	if ddocName == "" {
		fmt.Fprintf(os.Stderr, "No ddoc given\n")
		flag.Usage()
	}

	b, err := couchbase.GetBucket(*cbServ, "default", *cbBucket)
	maybeFatal(err, "Error connecting to couchbase: %v\n", err)

	j := json.RawMessage{}
	err = b.GetDDoc(ddocName, &j)
	maybeFatal(err, "Error getting ddoc: %v\n", err)

	buf := &bytes.Buffer{}
	err = json.Indent(buf, []byte(j), "", "  ")

	fmt.Printf("const %s = `%s`\n", *objName,
		strings.Replace(buf.String(), "`", "` + \"`\" + `", 0))
}