Enable serving of static files

This commit is contained in:
Lou Knauer 2021-09-21 16:06:41 +02:00
parent ad80e1373c
commit 341091a796

View File

@ -4,6 +4,7 @@ import (
"log" "log"
"net/http" "net/http"
"os" "os"
"flag"
"github.com/99designs/gqlgen/graphql/handler" "github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground" "github.com/99designs/gqlgen/graphql/playground"
@ -15,15 +16,15 @@ import (
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
) )
const defaultPort = "8080"
func main() { func main() {
port := os.Getenv("PORT") var port, staticFiles, jobDBFile string
if port == "" {
port = defaultPort
}
db, err := sqlx.Open("sqlite3", "./job.db") flag.StringVar(&port, "port", "8080", "Port on which to listen")
flag.StringVar(&staticFiles, "static-files", "./frontend/public", "Directory who's contents shall be served as static files")
flag.StringVar(&jobDBFile, "job-db", "./job.db", "SQLite 3 Jobs Database File")
flag.Parse()
db, err := sqlx.Open("sqlite3", jobDBFile)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -31,11 +32,16 @@ func main() {
r := mux.NewRouter() r := mux.NewRouter()
loggedRouter := handlers.LoggingHandler(os.Stdout, r) loggedRouter := handlers.LoggingHandler(os.Stdout, r)
srv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{DB: db}})) srv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{DB: db}}))
r.HandleFunc("/", playground.Handler("GraphQL playground", "/query")) r.HandleFunc("/graphql-playground", playground.Handler("GraphQL playground", "/query"))
r.Handle("/query", srv) r.Handle("/query", srv)
log.Printf("connect to http://localhost:%s/ for GraphQL playground", port) if len(staticFiles) != 0 {
r.PathPrefix("/").Handler(http.FileServer(http.Dir(staticFiles)))
}
log.Printf("connect to http://localhost:%s/graphql-playground for GraphQL playground", port)
log.Fatal(http.ListenAndServe("127.0.0.1:"+port, log.Fatal(http.ListenAndServe("127.0.0.1:"+port,
handlers.CORS(handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}), handlers.CORS(handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}),
handlers.AllowedMethods([]string{"GET", "POST", "HEAD", "OPTIONS"}), handlers.AllowedMethods([]string{"GET", "POST", "HEAD", "OPTIONS"}),