generated from VG-Tech-Dojo/hakaru
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
92 lines (72 loc) · 2 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
package main
import (
"fmt"
"log"
"net/http"
"strings"
"database/sql"
"os"
_ "github.com/go-sql-driver/mysql"
)
type DBStruct struct {
Name string
Value string
}
func initDB() *sql.DB {
dataSourceName := os.Getenv("HAKARU_DATASOURCENAME")
if dataSourceName == "" {
dataSourceName = "root:password@tcp(127.0.0.1:13306)/hakaru"
}
db, err := sql.Open("mysql", dataSourceName)
if err != nil {
panic(err.Error())
}
return db
}
// BulkInsert is
func BulkInsert(resc []DBStruct, db *sql.DB) (err error) {
rescInterface := []interface{}{}
stmt := "INSERT INTO eventlog(at, name, value) values"
for _, value := range resc {
fmt.Println(value)
stmt += "(Now(),?,?),"
rescInterface = append(rescInterface, value.Name)
rescInterface = append(rescInterface, value.Value)
}
stmt = strings.TrimRight(stmt, ",")
_, err = db.Exec(stmt, rescInterface...)
return
}
func main() {
db := initDB()
defer db.Close()
// connectionする数を制限する
// RDS が 66 のConnectionができるので、5台のインスタンスを立てることを想定し、 66/5=15...1
db.SetMaxOpenConns(6)
var values []DBStruct
// t := time.Now()
hakaruHandler := func(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
value := r.URL.Query().Get("value")
values = append(values, DBStruct{Name: name, Value: value})
if len(values) > 10 {
go BulkInsert(values, db)
values = nil
}
origin := r.Header.Get("Origin")
if origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
} else {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Allow-Methods", "GET")
}
http.HandleFunc("/hakaru", hakaruHandler)
http.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) })
// start server
if err := http.ListenAndServe(":8081", nil); err != nil {
log.Fatal(err)
}
}