Skip to content

Instantly share code, notes, and snippets.

@corymartin
Created July 21, 2012 18:50
Show Gist options
  • Select an option

  • Save corymartin/3156752 to your computer and use it in GitHub Desktop.

Select an option

Save corymartin/3156752 to your computer and use it in GitHub Desktop.
Learning Go. First attempt at serving JSON.
package main
import (
"encoding/json"
"fmt"
"net/http"
)
// Learning Go
// First try at serving JSON
type Food struct {
Name string `json:"name"`
Price float32 `json:"price"`
}
func main() {
// Serving a slice
http.HandleFunc("/foods", func(w http.ResponseWriter, r *http.Request) {
foods := []Food{
{"Taco", 3.99},
{"Burrito", 6.29},
{"Fajita", 12.49},
{"Enchilada", 9.75},
}
foodsJson, err := json.Marshal(&foods)
if err != nil {
fmt.Println("/foods error: ", err)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, string(foodsJson))
})
// Serving a simple object
http.HandleFunc("/taco", func(w http.ResponseWriter, r *http.Request) {
taco := Food{Name: "Chicken Paprika", Price: 3.49}
tacoJson, err := json.Marshal(taco)
if err != nil {
fmt.Println("/taco error: ", err)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, string(tacoJson))
})
err := http.ListenAndServe("localhost:9090", nil)
if err != nil {
fmt.Println("ListenAndServe Error: ", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment