test_utils.go 812 B

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