Asking a Golang question as someone coming from the Ruby & JS worlds, so bear with me if this is a rather simple Go question :)
Working with the Gorilla toolkit on an API, and I'm not sure if my thinking is totally correct on something. I've been reading through the thoroughly-excellent The Go Programming Language, but am decidedly not expert at Go yet. When sending back a JSON response, I've been doing something like the below to send back an object like this:
{ "healthy": true, "version": "0.0.1" }
But I'm not sure if it's a best practice or idiomatic to go to be creating one-off structures like appHealth or if I'm thinking too-much like I would in JS, where I'd just throw up an object literal and return the JSON-ified version of that to the client. Teach me, wise gophers.
Thank you!
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
)
type appHealth struct {
Healthy bool
Version string
}
func health(w http.ResponseWriter, r *http.Request) {
health := appHealth{true, "0.0.1"}
json.NewEncoder(w).Encode(health)
}
func main() {
port := os.Getenv("PORT")
router := mux.NewRouter().StrictSlash(false)
router.HandleFunc("/health", health)
log.Fatal(http.ListenAndServe(":"+port, router))
}
Encode.bytes.Buffer) first, and if there are no errors,io.Copy(buf, w)to write it out. Probably overkill for a simple data structure like this, but useful when dealing with more complex data (e.g. large structures from a DB -> JSON).