Skip to content

Instantly share code, notes, and snippets.

@c-j-j
Created January 9, 2016 15:35
Show Gist options
  • Save c-j-j/3dd9d10e3d5ea96ec1b5 to your computer and use it in GitHub Desktop.
Save c-j-j/3dd9d10e3d5ea96ec1b5 to your computer and use it in GitHub Desktop.
Json marshalling/unmarshalling with HTTP Get using Go
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type person struct {
UserId int `json:"userId"`
Id int `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
type people []person
func main() {
fmt.Printf("Listening on port 8080")
http.HandleFunc("/test", func(responseWriter http.ResponseWriter, request *http.Request) {
responseWriter.Write([]byte("Hello"))
persons, err := query()
if err != nil {
http.Error(responseWriter, err.Error(), 500)
}
hello := people{person{}, person{}}
fmt.Print(hello)
topFivePeople := persons[0:5]
responseWriter.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(responseWriter).Encode(topFivePeople)
})
http.ListenAndServe(":8080", nil)
}
func query() ([]person, error) {
response, err := http.Get("http://jsonplaceholder.typicode.com/posts")
if err != nil {
return []person{}, err
}
defer response.Body.Close()
var persons = people{}
if err := json.NewDecoder(response.Body).Decode(&persons); err != nil {
return []person{}, err
}
return persons, nil
}
func handler(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("This is an example server.\n"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment