Beispiel #1
0
func TestJsonFileRead(t *testing.T) {
	wd, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}
	filename := filepath.Join(wd, test_jsonfile)

	// Read non-existent file
	err = os.Remove(filename)
	if err != nil && !os.IsNotExist(err) {
		t.Fatal(err)
	}
	var foo fooStruct = fooStruct{60}
	err = util.ReadJsonFromFile(filename, &foo)
	if !os.IsNotExist(err) {
		t.Fatal(err)
	}
	if foo.BarBaz != 60 {
		t.Fatal(foo)
	}

	// Read bad file
	var data []byte = []byte("BAD-JSON")
	err = ioutil.WriteFile(filename, data, 0666)
	if err != nil {
		t.Fatal(err)
	}
	err = util.ReadJsonFromFile(filename, &foo)
	if err.Error() != "invalid character 'B' looking for beginning of value" {
		t.Fatal(err)
	}
	if foo.BarBaz != 60 {
		t.Fatal(foo)
	}

	// Read good file
	data = []byte("{\"barBaz\": 201}")
	err = ioutil.WriteFile(filename, data, 0666)
	if err != nil {
		t.Fatal(err)
	}
	err = util.ReadJsonFromFile(filename, &foo)
	if err != nil {
		t.Fatal(err)
	}
	if foo.BarBaz != 201 {
		t.Fatal(foo)
	}
}
Beispiel #2
0
// Json file implementation of RaftPersistentState.
//
// The returned instance is safe for access from multiple goroutines.
//
// The file access is NOT concurrency safe (from this or from another process).
//
// Writes to "filename" and also "filename.bak" using SafeWriteJsonToFile().
func NewJsonFileRaftPersistentState(filename string) (RaftPersistentState, error) {
	jfrps := &JsonFileRaftPersistentState{
		&sync.Mutex{}, filename, rps{0, ""},
	}

	err := util.ReadJsonFromFile(filename, &jfrps.rps)
	if err != nil {
		if os.IsNotExist(err) {
			jfrps.rps.CurrentTerm = 0
			jfrps.rps.VotedFor = ""
		} else {
			return nil, err
		}
	}

	return jfrps, nil
}