Created
September 25, 2016 17:41
-
-
Save cawa0505/6380bf625d7e44e5c0c172fedade6aa0 to your computer and use it in GitHub Desktop.
This file contains 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( | |
"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) | |
} | |
} | |
} |
This file contains 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 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