Skip to content

Instantly share code, notes, and snippets.

@cawa0505
Created September 25, 2016 17:41
Show Gist options
  • Save cawa0505/6380bf625d7e44e5c0c172fedade6aa0 to your computer and use it in GitHub Desktop.
Save cawa0505/6380bf625d7e44e5c0c172fedade6aa0 to your computer and use it in GitHub Desktop.
package main
import(
"fmt"
"tool/ubike"
"strconv"
)
type Station struct {
Act string
Ar string
Aren string
Bemp string
Lat string
Lng string
Mday string
Sarea string
Sareaen string
Sbi string
Sna string
Snaen string
Sno string
Tot string
}
func main() {
API := new(ubike.API)
data, err := API.GetStations()
if( err != nil ) {
fmt.Println(err)
}
stations := data.RetVal
fmt.Println("== 還有 Ubike 的地方 ==>")
for _, record := range stations {
if rec, ok := record.(map[string]interface{}); ok {
bemp, _ := strconv.ParseInt(rec["bemp"].(string), 10, 32)
if bemp > 0 {
fmt.Printf("[%s]: %d 台 (%s)\n", rec["sna"], bemp, rec["mday"])
}
} else {
fmt.Printf("record not a map[string]interface{}: %v\n", record)
}
}
}
package ubike
import(
"encoding/json"
"fmt"
"net/http"
"io/ioutil"
)
const (
VERSION = 1
UBIKE_JSON = "http://data.taipei/youbike"
)
type StationsResponse struct {
RetCode int `json:"retCode"`
RetVal map[string]interface{} `json:"retVal"`
}
type API struct {
}
func (r API) GetStations() (*StationsResponse,error) {
body, err := MakeRequest("http://data.taipei/youbike")
if (err != nil) {
return nil, err
}
s, err := ParseStations(body)
return s, err
}
func MakeRequest(url string) ([]byte, error) {
res, err := http.Get(url)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return []byte(body), err
}
func ParseStations(body []byte) (*StationsResponse, error) {
var s = new(StationsResponse)
err := json.Unmarshal(body, &s)
if(err != nil){
fmt.Println("whoops:", err)
}
return s, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment