Last active
September 14, 2023 20:51
-
-
Save crhntr/b2345902e225c3efdac61f902029fbca to your computer and use it in GitHub Desktop.
My answer to a slack question: "Anyone know of a package for parsing semi-structured queries of the style title:something description:"something else" visibility:public?"
This file contains 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" | |
"strings" | |
"text/scanner" | |
) | |
func main() { | |
src := `title:something description:"something else" visibility:public` | |
var s scanner.Scanner | |
s.Init(strings.NewReader(src)) | |
const ( | |
keyState = iota | |
sepState | |
valState | |
) | |
state := keyState | |
result := make(map[string]string) | |
var key string | |
for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() { | |
switch state { | |
case keyState: | |
key = s.TokenText() | |
state = sepState | |
case sepState: | |
state = valState | |
case valState: | |
val := s.TokenText() | |
if v, err := strconv.Unquote(val); err == nil { | |
val = v | |
} | |
result[key] = val | |
state = keyState | |
key = "" | |
} | |
} | |
fmt.Printf("%+v\n", result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote this circa 2019 in response to a slack message from a co-worker.