-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
109 lines (93 loc) · 2.02 KB
/
Copy pathmain.go
File metadata and controls
109 lines (93 loc) · 2.02 KB
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
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"time"
_ "github.com/go-sql-driver/mysql"
log "github.com/sirupsen/logrus"
"github.com/vrischmann/envconfig"
// "k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth"
)
// Env from environment variables or arguments
type Env struct {
Port string `envconfig:"default=3003"`
DbConn string `envconfig:""`
}
// Row defines a single mysql row
type Row struct {
ID int32 `json:"id"`
Name string `json:"name"`
}
// DataHandler implements http.Handler
type DataHandler struct {
db *sql.DB
}
func main() {
var env Env
log.Info("starting")
//var cl kubernetes.Interface
//b := cl.BatchV1beta1().CronJobs("")
//fmt.Println(b)
err := envconfig.Init(&env)
if err != nil {
log.Panic(err)
panic(err)
}
db, err := sql.Open("mysql", env.DbConn)
if err != nil {
panic(err)
}
defer db.Close()
db.SetConnMaxLifetime(time.Minute * 3)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
h := DataHandler{db: db}
err = http.ListenAndServe(fmt.Sprintf(":%s", env.Port), h)
if err != nil {
log.Error(err)
}
}
func (h DataHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
ctx := context.Background()
conn, err := h.db.Conn(ctx)
if err != nil {
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer conn.Close()
rows, err := conn.QueryContext(ctx, "select id, name from demo.product")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Error(err)
return
}
defer rows.Close()
var (
data []Row
id int32
name string
)
for rows.Next() {
err = rows.Scan(&id, &name)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Error(err)
return
}
data = append(data, Row{ID: id, Name: name})
}
body, err := json.Marshal(data)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Error(err)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write(body)
}