Skip to content

Instantly share code, notes, and snippets.

@tleyden
Created December 21, 2013 00:42
Show Gist options
  • Save tleyden/8063905 to your computer and use it in GitHub Desktop.
Save tleyden/8063905 to your computer and use it in GitHub Desktop.
satoshidb
package satoshidb
import (
"appengine"
"appengine/taskqueue"
"appengine/urlfetch"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
)
func init() {
http.HandleFunc("/", handler)
http.HandleFunc("/tasks/create_poll_tasks", createPollTasks)
http.HandleFunc("/tasks/poll_bitstamp_api", pollBitstampApi)
http.HandleFunc("/tasks/push_cb_cloud", pushCbCloud)
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Move along, nothing to see.")
}
// Push the price data to couchbase cloud
func pushCbCloud(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.NotFound(w, r)
return
}
c := appengine.NewContext(r)
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
body := r.FormValue("body")
c.Debugf("body %v", body)
// TODO: push to couchbase cloud
}
// Get price data from bitstamp API and save it in push_cb_cloud queue
func pollBitstampApi(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
// Get Content
client := urlfetch.Client(c)
resp, err := client.Get("https://www.bitstamp.net/api/ticker/")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
c.Errorf("Failed to get: %v", err.Error())
return
}
// Read Body
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
c.Errorf("Failed to read response: %v", err.Error())
return
}
// Add new task to push_cb_cloud queue
endpoint := "/tasks/push_cb_cloud"
v := url.Values{}
v.Set("body", string(body))
t := taskqueue.NewPOSTTask(endpoint, v)
if _, err := taskqueue.Add(c, t, "cbcloud"); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
c.Errorf("Failed to enqueue to push_cb_cloud: %v", err.Error())
return
}
c.Debugf("HTTP GET returned status %v", resp.Status)
}
// Generate the tasks to making polling request to bitstamp API to get prices.
// Called every minute by cron, and will create several tasks to run this minute
func createPollTasks(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
endpoint := "/tasks/poll_bitstamp_api"
for i := 0; i < 60; i += 5 {
t := taskqueue.NewPOSTTask(endpoint, nil)
t.Delay = time.Duration(i) * time.Second
if _, err := taskqueue.Add(c, t, "bitstamp"); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
c.Debugf("Added a new task with delay: %d", i)
}
fmt.Fprint(w, "Added a new tasks")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment