/
main.go
283 lines (248 loc) · 7.8 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"os"
"reflect"
log "github.com/parampavar/estimationgame/Godeps/_workspace/src/github.com/cihub/seelog"
_ "github.com/parampavar/estimationgame/Godeps/_workspace/src/github.com/lib/pq"
"github.com/parampavar/estimationgame/Godeps/_workspace/src/gopkg.in/redis.v3"
"github.com/parampavar/estimationgame/models"
)
//import "github.com/parampavar/estimationgame/Godeps/_workspace/src/gopkg.in/redis.v3"
import "strconv"
const (
DB_USER = "u311d07be533d42da8c704a4c29f0d573"
DB_PASSWORD = "c9e75db43e744176a5970138c3b7f080"
DB_LOCATION = "10.72.6.110:5432"
DB_NAME = "d311d07be533d42da8c704a4c29f0d573"
DB_SSLMODE = "disable" //verify-full"
)
const (
DEFAULT_PORT = "9000"
)
var isInCloud = false
// redisConnectAddrt
var client *redis.Client
var pgDbConnectionString = fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s", "postgres", "postgres", "localhost", "postgres", "disable")
var redisConnectAddr = fmt.Sprintf("%s:%s", "localhost", "6379")
var redisConnectPassword = ""
var redisConnectPort float64 = 6379
func FloatToString(input_num float64, number_of_decimals int) string {
// to convert a float number to a string
return strconv.FormatFloat(input_num, 'f', number_of_decimals, 64)
}
func RedisInit() {
// client = redis.NewClient(&redis.Options{
// Addr: redisConnectAddr,
// })
log.Info("RedisInit Started...")
log.Info("RedisInit connecting to " + redisConnectAddr + ", password: " + redisConnectPassword)
client := redis.NewClient(&redis.Options{
Addr: redisConnectAddr,
Password: redisConnectPassword,
DB: 0, // use default DB
})
client.FlushDb()
}
func RedisGetValue(key string) (interface{}, error) {
val, err := client.Get(key).Result()
if err == redis.Nil {
log.Info("'" + key + "' does not exists")
val = ""
} else if err != nil {
log.Info(err)
val = ""
} else {
log.Info("'" + key + "' exists with val='" + val + "'")
}
return val, err
}
func RedisSetValue(key string, val interface{}) error {
err := client.Set(key, val, 0).Err()
if err != nil {
log.Info(err)
}
return err
}
// Redis related - End
func HomeHandler(w http.ResponseWriter, r *http.Request) {
log.Info("HomeHandler Starting")
fmt.Fprintln(w, "Hello, myWorld!n")
log.Info("HomeHandler Ending")
}
func getDBData(tbl string) (interface{}, error) {
var rows interface{}
var err error
var db *sql.DB
var getFromDB = false
if isInCloud == true {
rows, err = RedisGetValue(tbl)
if err == redis.Nil {
log.Info("getDBData: Data not in Redis cache. Getting from DB.")
getFromDB = true
}
} else {
getFromDB = true
}
if getFromDB == true {
log.Info("getDBData: DB ConnectString = ", pgDbConnectionString)
db, err = sql.Open("postgres", pgDbConnectionString)
if err != nil {
log.Info(err)
}
log.Info("getDBData: DB Connection successful")
err = db.Ping()
if err != nil {
log.Info("getDBData: Ping error")
log.Info(err) // log.Critical(err)
}
log.Info("getDBData: DB Ping successful")
rows, err = db.Query("SELECT * FROM " + tbl)
if err != nil {
log.Info("getDBData: Query error")
log.Info(err) // log.Critical(err)
}
log.Info("getDBData: DB Query successful")
if isInCloud == true {
log.Info("getDBData: Storing in Redis")
RedisSetValue(tbl, rows)
}
// fmt.Fprintf(w, "Rows of "+tbl)
// log.Info("DB Reading thru the rows")
}
return rows, err
}
func DBHandler(w http.ResponseWriter, r *http.Request) {
tbl := "tbl" + r.URL.Path[1:len(r.URL.Path)] //Get the table name from the url
log.Info("DBHandler url.Path=" + tbl)
genrows, err := getDBData(tbl)
if err != nil {
log.Info("DBHandler getDBData error")
log.Info(err)
}
retString := ""
if rows, ok := genrows.(*sql.Rows); ok {
log.Info("DBHandler genrows is sql.Rows")
if "tbltoy" == tbl {
grows, err := models.ScanToys(rows) // ScanUsers was auto-generated!
if err != nil {
log.Info(err)
}
retString = models.ToysJson(grows)
}
if "tbltool" == tbl {
grows, err := models.ScanTools(rows) // ScanUsers was auto-generated!
if err != nil {
log.Info(err)
}
retString = models.ToolsJson(grows)
}
if "tbluser" == tbl {
grows, err := models.ScanUsers(rows) // ScanUsers was auto-generated!
if err != nil {
log.Info(err)
}
retString = models.UsersJson(grows)
}
} else {
/* not sql.Rows */
log.Info("DBHandler genrows is NOT sql.Rows")
log.Info(reflect.TypeOf(genrows))
log.Info("DBHandler genrows is NOT sql.Rows")
}
// if "tbltool" == tbl {
// grows, err := models.ScanTools(rows) // ScanUsers was auto-generated!
// }
log.Info(retString)
fmt.Fprintf(w, retString)
w.Write([]byte("Gorilla2\n"))
}
func main() {
defer log.Flush()
log.Info("App Started")
var appUrl = "http://localhost"
var port = ""
vcapApplication := os.Getenv("VCAP_APPLICATION")
if vcapApplication == "" {
log.Info("App Running locally.......")
if port = os.Getenv("PORT"); len(port) == 0 {
log.Info("Warning: PORT not set. Defaulting to ", DEFAULT_PORT)
port = DEFAULT_PORT
}
appUrl = appUrl + ":" + port
} else {
log.Info("App Running in the cloud.......")
var vcapApplicationJson map[string]interface{}
_ = json.Unmarshal([]byte(vcapApplication), &vcapApplicationJson)
appUrls := vcapApplicationJson["application_uris"].([]interface{})
appUrl = "http://" + appUrls[0].(string)
log.Info("application_uris=" + appUrl)
pgDbConnectionString = fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s", DB_USER, DB_PASSWORD, DB_LOCATION, DB_NAME, DB_SSLMODE)
isInCloud = true
if port = os.Getenv("PORT"); len(port) == 0 {
log.Info("Warning: PORT not set. Defaulting to ", DEFAULT_PORT)
port = DEFAULT_PORT
}
appUrl = appUrl + ":" + port
log.Info("Getting VCAP_SERVICES")
vcapServices := os.Getenv("VCAP_SERVICES")
if vcapServices == "" {
log.Info("No services bound to this application")
} else {
var vcapServicesJson map[string]interface{}
_ = json.Unmarshal([]byte(vcapServices), &vcapServicesJson)
cloudRedis := vcapServicesJson["redis-2"].([]interface{})
log.Info(cloudRedis)
cloudRedisMap := cloudRedis[0].(map[string]interface{})
cloudRedisCredentialsMap := cloudRedisMap["credentials"].(map[string]interface{})
log.Info(cloudRedisCredentialsMap["host"].(string))
redisConnectAddr = cloudRedisCredentialsMap["host"].(string)
log.Info(redisConnectAddr)
redisConnectPassword = cloudRedisCredentialsMap["password"].(string)
log.Info(redisConnectPassword)
redisConnectPort = cloudRedisCredentialsMap["port"].(float64)
log.Info(redisConnectPort)
redisConnectAddr = redisConnectAddr + ":" + FloatToString(redisConnectPort, 0)
log.Info(redisConnectAddr)
log.Info("Connecting to redis")
RedisInit()
//RedisGetValue("abced")
RedisSetValue("abced", "1111111111111111111111111111111")
// val, _ := RedisGetValue("abced")
// log.Info(val)
// RedisGetValue("abced")
// log.Info("Connecting to redis successful")
}
}
// log.Info("Connecting to redis")
// Init()
// RedisGetValue("abced")
// RedisSetValue("abced", "1111111111111111111111111111111")
// val, _ := RedisGetValue("abced")
// log.Info(val)
// RedisGetValue("abced")
// // if err != nil {
// // log.Info("Connecting to redis errored")
// // log.Info(err)
// // }
// log.Info("Connecting to redis successful")
// router := mux.NewRouter()
// router.HandleFunc("/", HomeHandler)
// router.HandleFunc("/db", DBHandler)
// // Bind to a port and pass our router in
// http.ListenAndServe(":8000", nil)
http.HandleFunc("/", HomeHandler)
http.HandleFunc("/home", HomeHandler)
http.HandleFunc("/user", DBHandler)
http.HandleFunc("/toy", DBHandler)
http.HandleFunc("/tool", DBHandler)
log.Info("App Started at " + appUrl)
//err := http.ListenAndServe("", nil)
err := http.ListenAndServe(":"+port, nil)
if err != nil {
log.Info("ListenAndServe: ", err)
}
}