Created
July 21, 2012 18:50
-
-
Save corymartin/3156752 to your computer and use it in GitHub Desktop.
Learning Go. First attempt at serving JSON.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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