本文整理汇总了Golang中encoding/json.Indent函数的典型用法代码示例。如果您正苦于以下问题:Golang Indent函数的具体用法?Golang Indent怎么用?Golang Indent使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Indent函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: printDebugOnfail
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")
}
}
}
}
开发者ID:Djuke,项目名称:httpapitester,代码行数:60,代码来源:test.go
示例2: AssertJSONBody
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()
}
}
开发者ID:ustrajunior,项目名称:minion,代码行数:30,代码来源:tst.go
示例3: MatchJSON
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
}
开发者ID:sguzwf,项目名称:mertiwiki,代码行数:32,代码来源:harness.go
示例4: Match
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
}
开发者ID:pivotal,项目名称:gumshoe,代码行数:32,代码来源:match_json_matcher.go
示例5: ContainsJSON
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
}
开发者ID:vsco,项目名称:http-test,代码行数:31,代码来源:assert_response.go
示例6: processJson
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
}
开发者ID:ewindfall,项目名称:go-liteide-tools,代码行数:27,代码来源:jsonfmt.go
示例7: CmdInspect
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
}
开发者ID:scottjg,项目名称:docker,代码行数:34,代码来源:commands.go
示例8: dumpRaw
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")
}
}
开发者ID:KeyOfSpectator,项目名称:hm9000,代码行数:29,代码来源:store.go
示例9: assertAst
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)
}
}
开发者ID:shitfSign,项目名称:akino,代码行数:34,代码来源:parse_test.go
示例10: main
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)
}
开发者ID:dwbuiten,项目名称:dumpindex,代码行数:30,代码来源:main.go
示例11: CmdInspect
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
}
开发者ID:jweede,项目名称:docker,代码行数:26,代码来源:commands.go
示例12: editReplicationController
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),
})
}
开发者ID:aclisp,项目名称:kubecon,代码行数:32,代码来源:main.go
示例13: Write
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
}
开发者ID:ymruan,项目名称:pact-go,代码行数:25,代码来源:pact_writer.go
示例14: main
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)
}
}
开发者ID:jonfk,项目名称:utility-belt,代码行数:25,代码来源:main.go
示例15: editNode
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),
})
}
开发者ID:aclisp,项目名称:kubecon,代码行数:30,代码来源:main.go
示例16: getUser
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)
*/
}
开发者ID:jonkeller,项目名称:OAuthExamples,代码行数:28,代码来源:authorization_code_grant.go
示例17: TemplateExport
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
}
开发者ID:seiji,项目名称:go-zabbix,代码行数:32,代码来源:templates.go
示例18: ExportSimulation
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
}
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:28,代码来源:hoverfly.go
示例19: CmdInspect
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
}
开发者ID:johnbellone,项目名称:docker,代码行数:35,代码来源:commands.go
示例20: ExampleIndent
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
// = }
// =]
}
开发者ID:2thetop,项目名称:go,代码行数:30,代码来源:example_test.go
注:本文中的encoding/json.Indent函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论