-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathmain.go
349 lines (287 loc) · 9.88 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"context"
"errors"
"fmt"
"os"
"time"
"encoding/json"
"log"
"net/http"
"strconv"
"strings"
//including gorilla mux and handlers packages for HTTP routing and CORS support
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
//connections to mongo
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"github.com/shirou/gopsutil/cpu"
"runtime"
)
const mongo_db = "langdb"
const mongo_collection = "languages"
const mongo_default_conn_str = "mongodb://mongo-0.mongo,mongo-1.mongo,mongo-2.mongo:27017/langdb"
const mongo_default_username = "admin"
const mongo_default_password = "password"
type codedetail struct {
Usecase string `json:"usecase,omitempty" bson:"usecase"`
Rank int `json:"rank,omitempty" bson:"rank"`
Compiled bool `json:"compiled" bson:"compiled"`
Homepage string `json:"homepage,omitempty" bson:"homepage"`
Download string `json:"download,omitempty" bson:"download"`
Votes int64 `json:"votes" bson:"votes"`
}
type language struct {
Name string `json:"name,omitempty" bson:"name"`
Detail codedetail `json:"codedetail,omitempty" bson:"codedetail"`
}
type voteresult struct {
Name string `json:"name"`
Votes int64 `json:"votes"`
}
var c *mongo.Client
func createlanguage(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
var detail codedetail
_ = json.NewDecoder(req.Body).Decode(&detail)
name := strings.ToLower(params["name"])
fmt.Printf("POST api call made to /languages/%s\n", name)
lang := language{name, detail}
id := insertNewLanguage(c, lang)
if id == nil {
_ = json.NewEncoder(w).Encode("{'result' : 'insert failed!'}")
} else {
err := json.NewEncoder(w).Encode(detail)
if err != nil {
http.Error(w, err.Error(), 400)
}
}
}
func getlanguages(w http.ResponseWriter, _ *http.Request) {
fmt.Println("GET api call made to /languages")
var langmap = make(map[string]*codedetail)
langs, err := returnAllLanguages(c, bson.M{})
if err != nil {
http.Error(w, err.Error(), 400)
}
for _, lang := range langs {
langmap[lang.Name] = &lang.Detail
}
err = json.NewEncoder(w).Encode(langmap)
if err != nil {
http.Error(w, err.Error(), 400)
}
}
func getlanguagebyname(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
name := strings.ToLower(params["name"])
fmt.Printf("GET api call made to /languages/%s\n", name)
lang, _ := returnOneLanguage(c, bson.M{"name": name})
if lang == nil {
_ = json.NewEncoder(w).Encode("{'result' : 'language not found'}")
} else {
err := json.NewEncoder(w).Encode(*lang)
if err != nil {
http.Error(w, err.Error(), 400)
}
}
}
func deletelanguagebyname(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
name := strings.ToLower(params["name"])
fmt.Printf("DELETE api call made to /languages/%s\n", name)
languagesRemoved := removeOneLanguage(c, bson.M{"name": name})
_ = json.NewEncoder(w).Encode(fmt.Sprintf("{'count' : %d}", languagesRemoved))
}
func voteonlanguage(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
name := strings.ToLower(params["name"])
fmt.Printf("GET api call made to /languages/%s/vote\n", name)
//example using go funcs + channels
//votesUpdated := updateVote(c, bson.M{"name": name})
vchan := voteChannel()
vchan <- name
voteCount, _ := strconv.ParseInt(<-vchan, 10, 64)
close(vchan)
w.Header().Set("Content-Type", "application/json")
voteresult := voteresult{
Name: name,
Votes: voteCount,
}
_ = json.NewEncoder(w).Encode(voteresult)
}
func voteChannel() (vchan chan string) {
//example using go funcs + channels
vchan = make(chan string)
go func() {
name := <-vchan
//fmt.Println(fmt.Sprintf("name is %s", name))
voteUpdated := strconv.FormatInt((updateVote(c, bson.M{"name": name})), 10)
vchan <- voteUpdated
}()
return vchan
}
func returnAllLanguages(client *mongo.Client, filter bson.M) ([]*language, error) {
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
client.Connect(ctx)
var langs []*language
collection := client.Database(mongo_db).Collection(mongo_collection)
cur, err := collection.Find(ctx, filter)
if err != nil {
return nil, errors.New("error querying documents from database")
}
for cur.Next(context.TODO()) {
var lang language
err = cur.Decode(&lang)
if err != nil {
return nil, errors.New("error on decoding the document")
}
langs = append(langs, &lang)
}
return langs, nil
}
func returnOneLanguage(client *mongo.Client, filter bson.M) (*language, error) {
var lang language
collection := client.Database(mongo_db).Collection(mongo_collection)
singleResult := collection.FindOne(context.TODO(), filter)
if singleResult.Err() == mongo.ErrNoDocuments {
return nil, errors.New("no documents found")
}
if singleResult.Err() != nil {
log.Println("Find error: ", singleResult.Err())
return nil, singleResult.Err()
}
singleResult.Decode(&lang)
return &lang, nil
}
func insertNewLanguage(client *mongo.Client, lang language) interface{} {
collection := client.Database(mongo_db).Collection(mongo_collection)
insertResult, err := collection.InsertOne(context.TODO(), lang)
if err != nil {
log.Fatalln("Error on inserting new language", err)
return nil
}
return insertResult.InsertedID
}
func removeOneLanguage(client *mongo.Client, filter bson.M) int64 {
collection := client.Database(mongo_db).Collection(mongo_collection)
deleteResult, err := collection.DeleteOne(context.TODO(), filter)
if err != nil {
log.Fatal("Error on deleting one Hero", err)
}
return deleteResult.DeletedCount
}
func updateVote(client *mongo.Client, filter bson.M) int64 {
upsert := true
after := options.After
opt := options.FindOneAndUpdateOptions{
ReturnDocument: &after,
Upsert: &upsert,
}
collection := client.Database(mongo_db).Collection(mongo_collection)
updatedData := bson.M{"$inc": bson.M{"codedetail.votes": 1}}
updatedResult := collection.FindOneAndUpdate(context.TODO(), filter, updatedData, &opt)
if updatedResult.Err() != nil {
log.Fatal("Error on updating language vote count", updatedResult.Err())
}
lang := language{}
_ = updatedResult.Decode(&lang)
return lang.Detail.Votes
}
//getClient returns a MongoDB Client
func getClient() *mongo.Client {
mongoconnstr := getEnv("MONGO_CONN_STR", mongo_default_conn_str)
mongousername := getEnv("MONGO_USERNAME", mongo_default_username)
mongopassword := getEnv("MONGO_PASSWORD", mongo_default_password)
fmt.Println("MongoDB connection details:")
fmt.Println("MONGO_CONN_STR:" + mongoconnstr)
fmt.Println("MONGO_USERNAME:" + mongousername)
fmt.Println("MONGO_PASSWORD:")
fmt.Println("attempting mongodb backend connection...")
clientOptions := options.Client().ApplyURI(mongoconnstr)
//test if auth is enabled or expected,
//for demo purposes when we setup mongo as a replica set using a StatefulSet resource in K8s auth is disabled
if clientOptions.Auth != nil {
clientOptions.Auth.Username = mongousername
clientOptions.Auth.Password = mongopassword
}
options.Client().SetMaxConnIdleTime(60000)
options.Client().SetHeartbeatInterval(5 * time.Second)
client, err := mongo.NewClient(clientOptions)
if err != nil {
log.Fatal(err)
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
return client
}
func init() {
c = getClient()
err := c.Ping(context.Background(), readpref.Primary())
if err != nil {
log.Fatal("couldn't connect to the database", err)
} else {
log.Println("connected!!")
}
}
func ok(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "OK!\n")
}
func version(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "API vTOKEN_VERSION\n")
}
func cpuDetails(w http.ResponseWriter, req *http.Request) {
// cpu - get CPU number of cores and speed
cpuStat, err := cpu.Info()
if err != nil {
fmt.Println(err)
}
runtimeOS := runtime.GOOS
fmt.Fprintf(w, "OS: %s\n", runtimeOS)
fmt.Fprintf(w, "CPU index number: %s\n", strconv.FormatInt(int64(cpuStat[0].CPU), 10))
fmt.Fprintf(w, "CPU index number: %s\n", strconv.FormatInt(int64(cpuStat[0].CPU), 10))
fmt.Fprintf(w, "VendorID: %s\n", cpuStat[0].VendorID)
fmt.Fprintf(w, "Family: %s\n", cpuStat[0].Family)
fmt.Fprintf(w, "Number of cores: %s\n", strconv.FormatInt(int64(cpuStat[0].Cores), 10))
fmt.Fprintf(w, "Model Name: %s\n", cpuStat[0].ModelName)
fmt.Fprintf(w, "Speed: %s\n", strconv.FormatFloat(cpuStat[0].Mhz, 'f', 2, 64))
}
func getEnv(key, fallback string) string {
value, exists := os.LookupEnv(key)
if !exists {
value = fallback
}
return value
}
func main() {
fmt.Println("version 1.01")
fmt.Println("serving on port 8080...")
fmt.Println("tests:")
fmt.Println("curl -s localhost:8080/ok")
fmt.Println("curl -s localhost:8080/cpu")
fmt.Println("curl -s localhost:8080/version")
fmt.Println("curl -s localhost:8080/languages")
fmt.Println("curl -s localhost:8080/languages | jq .")
router := mux.NewRouter()
//setup routes
router.HandleFunc("/languages/{name}", createlanguage).Methods("POST")
router.HandleFunc("/languages", getlanguages).Methods("GET")
router.HandleFunc("/languages/{name}", getlanguagebyname).Methods("GET")
router.HandleFunc("/languages/{name}", deletelanguagebyname).Methods("DELETE")
router.HandleFunc("/languages/{name}/vote", voteonlanguage).Methods("GET")
router.HandleFunc("/ok", ok).Methods("GET")
router.HandleFunc("/cpu", cpuDetails).Methods("GET")
router.HandleFunc("/version", version).Methods("GET")
//required for CORS - ajax API requests originating from the react browser vote app
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS"})
//listen on port 8080
log.Fatal(http.ListenAndServe(":8080", handlers.CORS(originsOk, headersOk, methodsOk)(router)))
}