Skip to content

Instantly share code, notes, and snippets.

@taskie
Created February 20, 2019 17:26
Show Gist options
  • Save taskie/fb6ba38ffd741838021a044740e327a0 to your computer and use it in GitHub Desktop.
Save taskie/fb6ba38ffd741838021a044740e327a0 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"os"
log "github.com/sirupsen/logrus"
)
func ScanValue(s string, format string) (interface{}, error) {
c := format[len(format)-1:]
switch c {
case "s", "c", "q":
var v string
fmt.Sscanf(s, format, &v)
return v, nil
case "d", "b", "o", "X", "x", "U":
var v int64
fmt.Sscanf(s, format, &v)
return v, nil
case "e", "E", "f", "g", "G":
var v float64
fmt.Sscanf(s, format, &v)
return v, nil
case "t":
var v bool
fmt.Sscanf(s, format, &v)
return v, nil
default:
return nil, fmt.Errorf("invalid format: %s", c)
}
}
func JsonStringify(v interface{}) string {
bs := new(bytes.Buffer)
err := json.NewEncoder(bs).Encode(v)
if err != nil {
panic(err)
}
return bs.String()
}
func main() {
inputFormat := "%s"
outputFormat := "json"
switch len(os.Args) {
case 0, 1:
break
case 2:
inputFormat = os.Args[1]
case 3:
inputFormat = os.Args[1]
outputFormat = os.Args[2]
default:
log.Fatalf("invalid arguments: %v", os.Args[3:])
}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
l := scanner.Text()
v, err := ScanValue(l, inputFormat)
if err != nil {
log.Error(err)
continue
}
if outputFormat == "json" {
fmt.Print(JsonStringify(v))
} else {
fmt.Printf(outputFormat+"\n", v)
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment