Skip to content

Instantly share code, notes, and snippets.

@henriquegogo
Last active January 9, 2019 19:48
Show Gist options
  • Save henriquegogo/75c4ea2f0c4bd97cf04670248400ecf9 to your computer and use it in GitHub Desktop.
Save henriquegogo/75c4ea2f0c4bd97cf04670248400ecf9 to your computer and use it in GitHub Desktop.
Make request and parse json into Go struct collection, map to another struct collection and print
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type gist struct {
ID string `json:"id"`
Description string `json:"description"`
User struct {
Name string `json:"login"`
} `json:"owner"`
}
type detail struct {
Key string
Creator string
Summary string
}
func getGists() []detail {
res, _ := http.Get("https://api.github.com/users/henriquegogo/gists")
defer res.Body.Close()
var gists []gist
json.NewDecoder(res.Body).Decode(&gists)
details := make([]detail, len(gists))
for i, item := range gists {
details[i] = detail{Key: item.ID, Creator: item.User.Name, Summary: item.Description}
}
return details
}
func main() {
http.HandleFunc("/", func(res http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(res, "<html><a href='/gists'>@henriquegogo gists</a><br /><a href='/about'>About</a></html>")
})
http.HandleFunc("/gists", func(res http.ResponseWriter, _ *http.Request) {
gists := getGists()
html := "<html><ul>"
for _, item := range gists {
html += "<li><a href='https://gist.github.com/henriquegogo/" + item.Key + "'>" + item.Summary + "</a> <i>(created by " + item.Creator + ")</i></li>"
}
html += "</ul></html>"
fmt.Fprintf(res, html)
})
http.HandleFunc("/about", func(res http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(res, "It's me!")
})
fmt.Println("Access: http://localhost:3000")
http.ListenAndServe(":3000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment