本文整理匯總了Golang中encoding/json.Indent函數的典型用法代碼示例。如果您正苦於以下問題:Golang Indent函數的具體用法?Golang Indent怎麽用?Golang Indent使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Indent函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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")
}
}
}
}
示例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()
}
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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
}
示例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")
}
}
示例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)
}
}
示例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)
}
示例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
}
示例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),
})
}
示例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
}
示例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)
}
}
示例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),
})
}