Skip to content

Instantly share code, notes, and snippets.

@maplebed
Created March 25, 2017 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maplebed/e9658e37cd01383b64dc9c4a3f87614a to your computer and use it in GitHub Desktop.
Save maplebed/e9658e37cd01383b64dc9c4a3f87614a to your computer and use it in GitHub Desktop.
Playing with logfmt go k=v parser library
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