-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
64 lines (54 loc) · 1.53 KB
/
http.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
package http
import (
"embed"
"io/fs"
"log"
"net/http"
"os"
"time"
)
type Application struct {
server *http.Server
infoLog *log.Logger
errorLog *log.Logger
templateFS fs.FS
}
func NewApplication(addr string, embeddedFiles embed.FS) (Application, error) {
app := Application{
server: &http.Server{
Addr: addr,
IdleTimeout: time.Minute,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
},
infoLog: log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime),
errorLog: log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile),
}
templateFS, err := fs.Sub(embeddedFiles, "templates")
if err != nil {
return Application{}, err
}
app.templateFS = templateFS
staticFiles, err := fs.Sub(embeddedFiles, "static")
if err != nil {
return Application{}, err
}
router := http.NewServeMux()
router.HandleFunc("/", app.handleGetIndex)
router.HandleFunc("/api/scale", app.handleGetScale)
router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFiles))))
app.server.Handler = router
return app, nil
}
func (a Application) Run() error {
a.infoLog.Printf("starting application at port %s", a.server.Addr)
return a.server.ListenAndServe()
}
func (a Application) internalServerError(err error, w http.ResponseWriter) {
a.errorLog.Println(err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
func (a Application) badRequest(err error, w http.ResponseWriter) {
a.errorLog.Println(err)
http.Error(w, "Bad Request", http.StatusBadRequest)
}