1
0
mirror of https://github.com/mattermost/focalboard.git synced 2024-12-18 09:35:25 +02:00
focalboard/server/web/webserver.go

101 lines
2.2 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"
)
// RoutedService defines the interface that is needed for any service to
// register themself in the web server to provide new endpoints. (see
// AddRoutes).
2020-10-16 11:41:56 +02:00
type RoutedService interface {
RegisterRoutes(*mux.Router)
}
// Server is the structure responsible for managing our http web server.
type Server struct {
http.Server
2020-10-16 16:21:42 +02:00
rootPath string
port int
ssl bool
2020-10-16 11:41:56 +02:00
}
// NewServer creates a new instance of the webserver.
func NewServer(rootPath string, port int, ssl bool) *Server {
2020-10-16 11:41:56 +02:00
r := mux.NewRouter()
ws := &Server{
Server: http.Server{
Addr: fmt.Sprintf(`:%d`, port),
Handler: r,
},
2020-10-16 16:21:42 +02:00
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 *Server) Router() *mux.Router {
return ws.Server.Handler.(*mux.Router)
}
// AddRoutes allows services to register themself in the webserver router and provide new endpoints.
func (ws *Server) AddRoutes(rs RoutedService) {
rs.RegisterRoutes(ws.Router())
2020-10-16 11:41:56 +02:00
}
func (ws *Server) 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"))
})
}
// Start runs the web server and start listening for charsetnnections.
func (ws *Server) Start() error {
ws.registerRoutes()
2020-10-16 11:41:56 +02:00
isSSL := ws.ssl && fileExists("./cert/cert.pem") && fileExists("./cert/key.pem")
2020-10-16 11:41:56 +02:00
if isSSL {
log.Printf("https server started on :%d\n", ws.port)
err := ws.ListenAndServeTLS("./cert/cert.pem", "./cert/key.pem")
2020-10-16 11:41:56 +02:00
if err != nil {
return err
}
2020-10-16 11:41:56 +02:00
return nil
}
2020-11-09 22:53:25 +02:00
log.Printf("http server started on :%d\n", ws.port)
err := ws.ListenAndServe()
2020-10-16 11:41:56 +02:00
if err != nil {
return err
}
2020-10-16 11:41:56 +02:00
return nil
}
func (ws *Server) Shutdown() error {
return ws.Close()
}
// 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
}