forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jscfg.go
44 lines (38 loc) · 1.2 KB
/
jscfg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package jscfg implements a simple API for reading and writing JSON files.
package jscfg
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/youtube/vitess/go/ioutil2"
)
func ToJson(val interface{}) string {
data, err := json.MarshalIndent(val, "", " ")
// This is not strictly the spirit of panic. This is meant to be used
// where it would be a programming error to have json encoding fail.
if err != nil {
panic(err)
}
return string(data)
}
// Atomically write a marshaled structure to disk.
func WriteJson(filename string, val interface{}) error {
data, err := json.MarshalIndent(val, " ", " ")
if err != nil {
return fmt.Errorf("WriteJson failed: %v %v", filename, err)
}
return ioutil2.WriteFileAtomic(filename, data, 0660)
}
func ReadJson(filename string, val interface{}) error {
data, err := ioutil.ReadFile(filename)
if err != nil {
return fmt.Errorf("ReadJson failed: %T %v", val, err)
}
if err = json.Unmarshal(data, val); err != nil {
return fmt.Errorf("ReadJson failed: %T %v %v", val, filename, err)
}
return nil
}