github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/common/test_utils.go (about) 1 package common 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io/ioutil" 7 ) 8 9 // LoadJSON reads the given file and unmarshals its content. 10 func LoadJSON(file string, val interface{}) error { 11 content, err := ioutil.ReadFile(file) 12 if err != nil { 13 return err 14 } 15 if err := json.Unmarshal(content, val); err != nil { 16 if syntaxerr, ok := err.(*json.SyntaxError); ok { 17 line := findLine(content, syntaxerr.Offset) 18 return fmt.Errorf("JSON syntax error at %v:%v: %v", file, line, err) 19 } 20 return fmt.Errorf("JSON unmarshal error in %v: %v", file, err) 21 } 22 return nil 23 } 24 25 // findLine returns the line number for the given offset into data. 26 func findLine(data []byte, offset int64) (line int) { 27 line = 1 28 for i, r := range string(data) { 29 if int64(i) >= offset { 30 return 31 } 32 if r == '\n' { 33 line++ 34 } 35 } 36 return 37 }