59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sim-link-server/routes"
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
)
|
|
|
|
func loggingMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if strings.HasPrefix(r.URL.Path, "/api/") {
|
|
log.Printf("[%s] %s %s", r.RemoteAddr, r.Method, r.URL.Path)
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func main() {
|
|
initDBConnection()
|
|
defer db.Close()
|
|
|
|
syncResults()
|
|
|
|
rt := routes.NewRouter(db)
|
|
rt.Register(http.DefaultServeMux)
|
|
|
|
|
|
resultsDir := "../results"
|
|
fsResults := http.FileServer(http.Dir(resultsDir))
|
|
http.Handle("/results/", http.StripPrefix("/results/", fsResults))
|
|
|
|
frontendDir := "../build"
|
|
fsFrontend := http.FileServer(http.Dir(frontendDir))
|
|
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
path := filepath.Join(frontendDir, r.URL.Path)
|
|
_, err := os.Stat(path)
|
|
if os.IsNotExist(err) {
|
|
http.ServeFile(w, r, filepath.Join(frontendDir, "index.html"))
|
|
return
|
|
}
|
|
fsFrontend.ServeHTTP(w, r)
|
|
})
|
|
|
|
port := os.Getenv("PORT")
|
|
if port == "" {
|
|
port = "8080"
|
|
}
|
|
|
|
fmt.Println("Server listening on port", port)
|
|
loggedMux := loggingMiddleware(http.DefaultServeMux)
|
|
log.Fatal(http.ListenAndServe("0.0.0.0:"+port, loggedMux))
|
|
}
|