Created
January 9, 2016 15:35
-
-
Save c-j-j/3dd9d10e3d5ea96ec1b5 to your computer and use it in GitHub Desktop.
Json marshalling/unmarshalling with HTTP Get using Go
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" | |
) | |
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