Created
March 25, 2017 21:55
-
-
Save maplebed/e9658e37cd01383b64dc9c4a3f87614a to your computer and use it in GitHub Desktop.
Playing with logfmt go k=v parser library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strconv" | |
"github.com/davecgh/go-spew/spew" | |
"github.com/kr/logfmt" | |
) | |
// base test case | |
const t0 = `foo=bar` | |
// string, int, float, bool | |
const t1 = `foo=bar baz=3 fl=3.1415926535 bl=true` | |
// value has multiple words, unquoted | |
const t2 = `foo=bar ben=one two baz=3` | |
// value has a quoted string with spaces and an equals sign | |
const t3 = `foo=bar eq="a test with = signs" baz=3` | |
// value has an unquoted sign with no spaces but an equals sign | |
const t4 = `foo=bar unq=astr=with=equals?and*stuff baz=3` | |
func parseIntoMap(m map[string]interface{}, line []byte) error { | |
f := func(key, val []byte) error { | |
keyStr := string(key) | |
valStr := string(val) | |
if b, err := strconv.ParseBool(valStr); err == nil { | |
m[keyStr] = b | |
return nil | |
} | |
if i, err := strconv.Atoi(valStr); err == nil { | |
m[keyStr] = i | |
return nil | |
} | |
if f, err := strconv.ParseFloat(valStr, 64); err == nil { | |
m[keyStr] = f | |
return nil | |
} | |
m[keyStr] = valStr | |
return nil | |
} | |
handler := logfmt.HandlerFunc(f) | |
return logfmt.Unmarshal(line, handler) | |
} | |
func main() { | |
for i, str := range []string{t0, t1, t2, t3, t4} { | |
m := make(map[string]interface{}) | |
parseIntoMap(m, []byte(str)) | |
fmt.Printf("%d: `%s`\n", i, str) | |
spew.Dump(m) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment