-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
main.go
100 lines (85 loc) · 2.13 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
93
94
95
96
97
98
99
100
package main
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/simpleiot/simpleiot/api"
"github.com/simpleiot/simpleiot/assets/frontend"
"github.com/simpleiot/simpleiot/db"
)
// IndexHandler is used to serve the index page
type IndexHandler struct{}
func (h *IndexHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
fmt.Println("indexHandler")
f := frontend.Asset("/index.html")
if f == nil {
rw.WriteHeader(http.StatusNotFound)
} else {
var reader = bytes.NewBuffer(f)
io.Copy(rw, reader)
}
}
// NewIndexHandler returns a new Index handler
func NewIndexHandler() http.Handler {
return &IndexHandler{}
}
// App is a struct that implements http.Handler interface
type App struct {
PublicHandler http.Handler
IndexHandler http.Handler
V1ApiHandler http.Handler
}
// Top level handler for http requests in the coap-server process
func (h *App) ServeHTTP(res http.ResponseWriter, req *http.Request) {
var head string
fmt.Println("Path: ", req.URL.Path)
if req.URL.Path == "/" {
h.IndexHandler.ServeHTTP(res, req)
} else {
head, req.URL.Path = api.ShiftPath(req.URL.Path)
switch head {
case "public":
h.PublicHandler.ServeHTTP(res, req)
case "v1":
h.V1ApiHandler.ServeHTTP(res, req)
default:
http.Error(res, "Not Found", http.StatusNotFound)
}
}
}
// NewAppHandler returns a new application (root) http handler
func NewAppHandler(db *db.Db) http.Handler {
return &App{
PublicHandler: http.FileServer(frontend.FileSystem()),
IndexHandler: NewIndexHandler(),
V1ApiHandler: api.NewV1Handler(db),
}
}
func httpServer(port string, db *db.Db) error {
address := fmt.Sprintf(":%s", port)
log.Println("Starting http server")
return http.ListenAndServe(address, NewAppHandler(db))
}
func main() {
port := os.Getenv("SIOT_PORT")
if port == "" {
port = "8080"
}
dataDir := os.Getenv("SIOT_DATA")
if dataDir == "" {
dataDir = "./"
}
db, err := db.NewDb(dataDir)
if err != nil {
log.Println("Error opening db: ", err)
os.Exit(-1)
}
log.Println("Starting portal on port: ", port)
err = httpServer(port, db)
if err != nil {
log.Println("Error starting server: ", err)
}
}