focalboard/server/web/webserver.go

85 lines
1.6 KiB
Go
Raw Normal View History

package web
2020-10-16 11:41:56 +02:00
import (
"fmt"
"log"
"net/http"
"os"
"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)
}
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 {
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")
2020-10-16 11:41:56 +02:00
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
}
2020-10-16 11:41:56 +02:00
return nil
}
2020-10-16 11:41:56 +02:00
log.Println("http server started on ", urlPort)
err := http.ListenAndServe(urlPort, nil)
if err != nil {
return err
}
2020-10-16 11:41:56 +02:00
return nil
}
// 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
}