Skip to content

Instantly share code, notes, and snippets.

@kevinpostal
Created June 2, 2016 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinpostal/ae17a18466178c89cf1fab067cf07fe5 to your computer and use it in GitHub Desktop.
Save kevinpostal/ae17a18466178c89cf1fab067cf07fe5 to your computer and use it in GitHub Desktop.
package hello
import (
"html/template"
"encoding/json"
"io/ioutil"
"fmt"
"strings"
"net/http"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/bigquery/v2"
"google.golang.org/appengine"
"google.golang.org/appengine/urlfetch"
)
const PROJECTID = "kcrw-964"
const DATASET = "tracklist"
const JSON_PEM_PATH = "./KCRW-d2265593e923.json"
type StationTrackItem struct {
ExecutionTime string `json:"executionTime"`
AffiliateLinkiPhone string `json:"affiliateLinkiPhone"`
ProgramStart string `json:"program_start"`
AffiliateLinkSpotify string `json:"affiliateLinkSpotify"`
PlayId int `json:"play_id"`
Offset int `json:"offset"`
ProgramId string `json:"program_id"`
Datetime string `json:"datetime"`
ProgramEnd string `json:"program_end"`
AffiliateLinkRdio string `json:"affiliateLinkRdio"`
AlbumImage string `json:"albumImage"`
Year int `json:"year"`
Date string `json:"date"`
ProgramTitle string `json:"program_title"`
AlbumImageLarge string `json:"albumImageLarge"`
Album string `json:"album"`
Title string `json:"title"`
Artist string `json:"artist"`
Host string `json:"host"`
Comments string `json:"comments"`
Label string `json:"label"`
AffiliateLinkiTunes string `json:"affiliateLinkiTunes"`
ArtistUrl string `json:"artist_url"`
AffiliateLinkAmazon string `json:"affiliateLinkAmazon"`
Time string `json:"time"`
Channel string `json:"channel"`
}
func init() {
http.HandleFunc("/", handler)
http.HandleFunc("/kcrw/", listHandler)
}
func getStations(body []byte) ([]StationTrackItem, error) {
var data []StationTrackItem
err := json.Unmarshal(body, &data)
if(err != nil){
fmt.Println("whoops:", err)
}
return data, err
}
var rssTemplate = template.Must(template.New("Track").Parse(`
<html>
<head>
<title>Go Rss Template</title>
</head>
<body>
{{range .}}
{{if .Title}}
<pre>[{{.Time}}] {{.Title}}({{.Year}}) - <a href="{{.ArtistUrl}}">{{.Artist}}</a>
<img src="{{.AlbumImageLarge}}">
</pre>
{{end}}
{{end}}
</body>
</html>
`))
func handler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
// create a new App Engine context from the request.
ctx := appengine.NewContext(r)
// obtain the list of dataset names.
names, err := datasets(ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text")
if len(names) == 0 {
fmt.Fprintf(w, "no datasets visible")
} else {
fmt.Fprintf(w, "datasets:\n\t"+strings.Join(names, "\n\t"))
}
}
// datasets returns a list with the ids of all the Big Query datasets visible
// with the given context.
func datasets(ctx context.Context) ([]string, error) {
// create a new authenticated HTTP client over urlfetch.
client := &http.Client{
Transport: &oauth2.Transport{
Source: google.AppEngineTokenSource(ctx, bigquery.BigqueryScope),
Base: &urlfetch.Transport{Context: ctx},
},
}
// create the BigQuery service.
bq, err := bigquery.New(client)
if err != nil {
return nil, fmt.Errorf("could not create service: %v", err)
}
// obtain the current application id, the BigQuery id is the same.
appID := "kcrw-964" //appengine.AppID(ctx)
// prepare the list of ids.
var ids []string
datasets, err := bq.Datasets.List(appID).Do()
if err != nil {
return nil, fmt.Errorf("could not list datasets for %q: %v", appID, err)
}
for _, d := range datasets.Datasets {
ids = append(ids, d.Id)
}
return ids, nil
}
func listHandler(w http.ResponseWriter, r *http.Request) {
//var x map[string]interface{}
ctx := appengine.NewContext(r)
googleclient := urlfetch.Client(ctx)
response, err := googleclient.Get("http://tracklist-api.kcrw.com/Simulcast/all/1")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data, err := ioutil.ReadAll(response.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s, err := getStations(data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := rssTemplate.Execute(w, s); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// for i := range s {
// //fmt.Fprintf(w, "%#v", s[i].Title)
// fmt.Fprintf(w, "%# v", pretty.Formatter(s[i]))
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment