by dewey · 8y ago · 0 comments
1) You should really not build your json by manually building the string. That's very error prone and hard to extend.
fmt.Fprintf(f,
"{\n\t\"from\": {\n\t\t\"name\": \"%s\",
Use https://golang.org/pkg/encoding/json/ (https://gobyexample.com/json) instead. Working with json in Go is really one of the nicer features of Go (It's Go, not "GoLang")2) By setting / typoing a config option you could accidentally delete files from your computer, even your home directory
err := os.Remove(jsonfile)To assist in using JSON, you'll want to declare a struct holding all your config, at which point it becomes quite surprisingly simple to load it from and save it to a file.
Once you have that functionality, I suggest using it for your initial creation as well. I have a program here where I've been using the pattern that I create a default config sample within the program, and if I can't find the config you specify, I print out an error, and the sample JSON file that constitutes a full, legal config for the user's convenience. I wouldn't ship anything that I'd expect to end up in a Linux distro or something that way, but for an internal tool it seems a decent enough pattern.
Finally, I'd suggest reddit.com/r/golang is a better sort of place for this sort of thing if you want a review, and there's probably even better places, as I'm not convinced that a karma-based voting site is all that great for reviews for beginners. (It's really easy for a post like that to pick up a couple of early downvotes, and consequently lose all visibility to the people who are willing to help.) But if you're going to use one, /r/golang would be better.
I am not shipping it to any distro or something like that. I was using this for myself and just made it open source.
Thank you for taking your time and reviewing this. As for /r/golang, I will look into it. :)
People usually prefer "Go" or "Golang", I only mentioned it because I noticed it in the project description.
1) How do I format the JSON for readability or should I ignore that?
2) Thanks for that. Didn't know about it. Any ideas on how I can fix that? Maybe I can check if it is a file and not a directory and ask for input again for y/n?
1) What do you mean exactly? The usual way would be to keep your data in a struct like:
type configuration struct {
Name string `json:"name"`
}
and then marshall it into a json string like: https://play.golang.org/p/uWvwBY4h03nIf you need more details feel free to contact me. Address is in my profile.
Also, great website! :D
however i am a bit wary... my first "real" (but small) project in go was to process some xml. turns out the stdlib parser doesn't handle self-closing tags very well, and would simply not pick up some important content from files i was working with.
i would wager the json stuff is probably a much hotter code path so it's probably fine.