forked from AlperRehaYAZGAN/cn-turkey-workshop-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
58 lines (49 loc) · 1.24 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
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
// redis/v8
"github.com/go-redis/redis/v8"
// template
"html/template"
)
func main() {
// working directory
pwd, err := os.Getwd()
if err != nil {
log.Fatalln("error: unable to get current working directory")
}
// index.html
t, err := template.ParseFiles(pwd + "/templates/index.html")
if err != nil {
log.Fatalln("error: unable to parse index.html " + err.Error())
}
// redis environments
redisURL := os.Getenv("REDIS_URL")
redisPassword := os.Getenv("REDIS_PASSWORD")
appPort := os.Getenv("APP_PORT")
if redisURL == "" || redisPassword == "" || appPort == "" {
log.Fatalln("APP_PORT, REDIS_URL or REDIS_PASSWORD is not set")
}
// init redis conn
rContext := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: redisURL,
Password: redisPassword,
DB: 0,
})
// http handler
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// increment counter, render index.html with "Counter"
counter, _ := rdb.Incr(rContext, "counter").Result()
t.Execute(w, map[string]interface{}{
"Counter": counter,
})
})
// start server
fmt.Println("Server is starting on port " + appPort)
http.ListenAndServe(":"+appPort, nil)
}