Skip to content

Instantly share code, notes, and snippets.

@josephspurrier
Created February 1, 2016 22:26
Show Gist options
  • Save josephspurrier/1e3eb0f7632fe805fae5 to your computer and use it in GitHub Desktop.
Save josephspurrier/1e3eb0f7632fe805fae5 to your computer and use it in GitHub Desktop.
Encode File Contents as JSON String
package main
import (
"encoding/json"
"flag"
"io"
"io/ioutil"
"log"
"os"
)
type Output struct {
Content string
}
func readFile(configFile string) {
var err error
var input = io.ReadCloser(os.Stdin)
if input, err = os.Open(configFile); err != nil {
log.Fatalln(err)
}
// Read the config file
jsonBytes, err := ioutil.ReadAll(input)
input.Close()
if err != nil {
log.Fatalln(err)
}
f := &Output{
Content: string(jsonBytes),
}
b, _ := json.Marshal(f)
ioutil.WriteFile("output.txt", b, 0600)
log.Println("Wrote to file: output.txt")
}
func main() {
flag.Parse()
f := flag.Arg(0)
if f == "" {
log.Println("File is missing")
os.Exit(1)
}
readFile(f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment