2020-10-16 19:12:53 +02:00
|
|
|
package web
|
2020-10-16 11:41:56 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2020-10-16 19:12:53 +02:00
|
|
|
"os"
|
2020-10-18 02:46:25 +02:00
|
|
|
"path"
|
2020-10-16 11:41:56 +02:00
|
|
|
"path/filepath"
|
|
|
|
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
)
|
|
|
|
|
|
|
|
type RoutedService interface {
|
|
|
|
RegisterRoutes(*mux.Router)
|
|
|
|
}
|
|
|
|
|
|
|
|
type WebServer struct {
|
2020-10-16 16:21:42 +02:00
|
|
|
router *mux.Router
|
|
|
|
rootPath string
|
|
|
|
port int
|
|
|
|
ssl bool
|
2020-10-16 11:41:56 +02:00
|
|
|
}
|
|
|
|
|
2020-10-16 16:21:42 +02:00
|
|
|
func NewWebServer(rootPath string, port int, ssl bool) *WebServer {
|
2020-10-16 11:41:56 +02:00
|
|
|
r := mux.NewRouter()
|
|
|
|
|
2020-10-16 16:21:42 +02:00
|
|
|
ws := &WebServer{
|
|
|
|
router: r,
|
|
|
|
rootPath: rootPath,
|
|
|
|
port: port,
|
|
|
|
ssl: ssl,
|
2020-10-16 11:41:56 +02:00
|
|
|
}
|
2020-10-16 16:21:42 +02:00
|
|
|
|
|
|
|
return ws
|
2020-10-16 11:41:56 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (ws *WebServer) AddRoutes(rs RoutedService) {
|
|
|
|
rs.RegisterRoutes(ws.router)
|
|
|
|
}
|
|
|
|
|
2020-10-18 02:46:25 +02:00
|
|
|
func (ws *WebServer) registerRoutes() {
|
|
|
|
ws.router.PathPrefix("/static").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(filepath.Join(ws.rootPath, "static")))))
|
|
|
|
ws.router.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
|
|
http.ServeFile(w, r, path.Join(ws.rootPath, "index.html"))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-10-16 11:41:56 +02:00
|
|
|
func (ws *WebServer) Start() error {
|
2020-10-18 02:46:25 +02:00
|
|
|
ws.registerRoutes()
|
2020-10-16 11:41:56 +02:00
|
|
|
http.Handle("/", ws.router)
|
|
|
|
|
|
|
|
urlPort := fmt.Sprintf(`:%d`, ws.port)
|
|
|
|
var isSSL = ws.ssl && fileExists("./cert/cert.pem") && fileExists("./cert/key.pem")
|
|
|
|
if isSSL {
|
|
|
|
log.Println("https server started on ", urlPort)
|
|
|
|
err := http.ListenAndServeTLS(urlPort, "./cert/cert.pem", "./cert/key.pem", nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
log.Println("http server started on ", urlPort)
|
|
|
|
err := http.ListenAndServe(urlPort, nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-10-16 19:12:53 +02:00
|
|
|
// FileExists returns true if a file exists at the path
|
|
|
|
func fileExists(path string) bool {
|
|
|
|
_, err := os.Stat(path)
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return err == nil
|
|
|
|
}
|