-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
71 lines (54 loc) · 1.21 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
package main
import (
"code/plant-diary/handlers"
"database/sql"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
_ "github.com/mattn/go-sqlite3"
)
type Photo struct {
ID int64 `json:"photoId"`
Src string `json:"src"`
}
type PhotoCollection struct {
Photos []Photo `json:"items"`
}
var db *sql.DB
func main() {
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// initialize DB
db := initDB("database/plantingdiary.sqlite")
migrateDB(db)
// HTTP routes
e.File("/", "public/index.html")
e.GET("/photos", handlers.GetPhotos(db))
e.POST("/photos", handlers.UploadPhoto(db))
e.DELETE("/photos/:photoId", handlers.DeletePhoto(db))
e.Static("/uploads", "public/uploads")
e.Logger.Fatal(e.Start(":8080"))
}
// DB
func initDB(filepath string) *sql.DB {
db, err := sql.Open("sqlite3", filepath)
if err != nil {
panic("Error connecting to database")
}
if db == nil {
panic("db nil")
}
return db
}
func migrateDB(db *sql.DB) {
sql := `
CREATE TABLE IF NOT EXISTS photos(
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
src VARCHAR NOT NULL
);`
_, err := db.Exec(sql)
if err != nil {
panic(err)
}
}