github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/common/test_utils.go (about) 1 // This file is part of the go-sberex library. The go-sberex library is 2 // free software: you can redistribute it and/or modify it under the terms 3 // of the GNU Lesser General Public License as published by the Free 4 // Software Foundation, either version 3 of the License, or (at your option) 5 // any later version. 6 // 7 // The go-sberex library is distributed in the hope that it will be useful, 8 // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 10 // General Public License <http://www.gnu.org/licenses/> for more details. 11 12 package common 13 14 import ( 15 "encoding/json" 16 "fmt" 17 "io/ioutil" 18 ) 19 20 // LoadJSON reads the given file and unmarshals its content. 21 func LoadJSON(file string, val interface{}) error { 22 content, err := ioutil.ReadFile(file) 23 if err != nil { 24 return err 25 } 26 if err := json.Unmarshal(content, val); err != nil { 27 if syntaxerr, ok := err.(*json.SyntaxError); ok { 28 line := findLine(content, syntaxerr.Offset) 29 return fmt.Errorf("JSON syntax error at %v:%v: %v", file, line, err) 30 } 31 return fmt.Errorf("JSON unmarshal error in %v: %v", file, err) 32 } 33 return nil 34 } 35 36 // findLine returns the line number for the given offset into data. 37 func findLine(data []byte, offset int64) (line int) { 38 line = 1 39 for i, r := range string(data) { 40 if int64(i) >= offset { 41 return 42 } 43 if r == '\n' { 44 line++ 45 } 46 } 47 return 48 }