markthethomas
markthethomas

Reputation: 4431

Data Structures in Golang

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))
}

Upvotes: 0

Views: 279

Answers (1)

matt.s
matt.s

Reputation: 1736

Looks pretty good. Don't be afraid to make types for that will add to the meaning.

type Version string  

You can then have logic for what a version looks like that will be tied to the type

Or you might want to check out juju's version package.

If you really have a struct that is a one off, you can do an anonymous struct with a literal.

health := struct{ 
    Health bool
    Version string
}{
    true,
    "1.2.3",
}

Upvotes: 1

Related Questions