-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
75 lines (62 loc) · 1.47 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
package main
import (
"database/sql"
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"sync"
_ "github.com/go-sql-driver/mysql"
)
type templateHandler struct {
once sync.Once
filename string
db *sql.DB
templ *template.Template
}
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t.once.Do(func() {
t.templ =
template.Must(template.ParseFiles(filepath.Join("templates",
t.filename)))
})
rows, err := t.db.Query("SELECT * FROM `test`.comments")
if err != nil {
panic(err.Error())
}
defer rows.Close()
var comments []string
for rows.Next() {
var id int
var comment string
if err := rows.Scan(&id, &comment); err != nil {
log.Fatal(err)
} else {
comments = append(comments, comment)
}
}
t.templ.Execute(w, comments)
}
func main() {
dbHost := os.Getenv("DB_HOST")
db, err := sql.Open("mysql", "root@tcp("+dbHost+":3306)/")
if err != nil {
panic(err.Error())
}
defer db.Close()
db.Query("CREATE DATABASE IF NOT EXISTS `test`")
db.Query(`
CREATE TABLE test.comments (
id int(11) unsigned NOT NULL AUTO_INCREMENT,
text varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
`)
http.Handle("/", &templateHandler{filename: "index.html", db: db})
log.Println("Golang application starting on http://localhost:8080")
log.Println("Ctrl-C to shutdown server")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}