-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
67 lines (59 loc) · 1.54 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/joho/godotenv"
)
var accountKey string
func handler(w http.ResponseWriter, r *http.Request) {
busStopCode := r.FormValue("busStopCode")
log.Println("busStopCode: ", busStopCode)
w.Header().Set("Access-Control-Allow-Origin", "*")
url := fmt.Sprintf("http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2?BusStopCode=%v", busStopCode)
res := callBusAPI(url, accountKey)
//callBusAPI("http://datamall2.mytransport.sg/ltaodataservice/BusStops", accountKey)
bytes, err := w.Write(res)
if err != nil {
fmt.Println("error: ", err)
return
}
log.Println(bytes, "bytes written")
}
func getAccountKey() string {
godotenv.Load(".env")
return os.Getenv("accountkey")
}
func callBusAPI(url, accountKey string) []byte {
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil || req == nil {
log.Println("err: ", err)
return []byte{}
}
req.Header.Add("AccountKey", accountKey)
req.Header.Add("accept", "application/json")
res, err := client.Do(req)
if err != nil {
log.Println("error http get, err: ", err)
return []byte{}
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Println("fail to read all, err: ", err)
return []byte{}
}
log.Println("body:", string(body))
defer res.Body.Close()
fmt.Println("res:", res)
return body
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/nextBusStop", handler)
accountKey = getAccountKey()
log.Println("serving at 8082")
log.Fatal(http.ListenAndServe(":8082", mux))
}