-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
51 lines (45 loc) · 1.52 KB
/
utils.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
45
46
47
48
49
50
51
// Package utils holds common data structures and functions useful for working
// with OpenChirp.
package utils
import (
"encoding/csv"
"strconv"
"strings"
)
// ParseCSVConfig parses a single config field that follows comma and
// optional quotes seperated syntax into it's constituent tokens
// Possible errors returned are from the encoding/csv package.
// The error can be referenced by it's concrete type *csv.ParseError,
// which can give useful information about where the parse error occurred.
// Example: errColumn := err.(*csv.ParseError).Column
func ParseCSVConfig(configline string) ([]string, error) {
if configline == "" {
return []string{}, nil
}
r := csv.NewReader(strings.NewReader(configline))
r.TrimLeadingSpace = true
// Call Read only once because there should only be one line
tokens, err := r.Read()
return tokens, err
}
// ParseOCValue tries to parse the three typical primitive data types used
// in OpenChirp. It first tries to parse the value as a float64. Then,
// it tries to parse as a bool. If all else fails, it returns the value
// as a string.
func ParseOCValue(value string) interface{} {
// Try float64
if v, err := strconv.ParseFloat(value, 64); err == nil {
return v
}
// Try bool
if v, err := strconv.ParseBool(value); err == nil {
return v
}
// Take as string
return value
}
// FormatFloat64 formats the given float64 value using a dynamic precison
// that looks cleaner when sent back to OpenChirp
func FormatFloat64(f float64) string {
return strconv.FormatFloat(f, 'f', -1, 64)
}