78 lines
1.9 KiB
Go
78 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
"github.com/go-chi/cors"
|
|
"github.com/hhhapz/hackathon/api"
|
|
"github.com/hhhapz/hackathon/auth"
|
|
"github.com/hhhapz/hackathon/db"
|
|
"github.com/peterbourgon/ff/v3"
|
|
)
|
|
|
|
func run() error {
|
|
fs := flag.NewFlagSet("hackathon", flag.ExitOnError)
|
|
port := fs.Int("port", 8080, "HTTP Server Port")
|
|
secretFile := fs.String("secret", "client.secret.json", "Path to google oauth2 secret credentials JSON file.")
|
|
dbFile := fs.String("db", "db.sqlite", "Path to sqlite3 database file")
|
|
if err := ff.Parse(fs, os.Args[1:], ff.WithEnvVarPrefix("HK")); err != nil {
|
|
return err
|
|
}
|
|
|
|
if *secretFile == "" {
|
|
return fmt.Errorf("location to secret credentials file not provided.\nTry -h")
|
|
}
|
|
|
|
database, err := db.NewDB(*dbFile)
|
|
if err != nil {
|
|
return fmt.Errorf("could not open db: %v", err)
|
|
}
|
|
|
|
oaStore := db.NewOAuthState()
|
|
oaConfig, err := auth.NewOauthConfig(*secretFile)
|
|
if err != nil {
|
|
return fmt.Errorf("could not create oauth config: %w", err)
|
|
}
|
|
|
|
server := api.NewServer(oaConfig, oaStore, database)
|
|
|
|
r := chi.NewRouter()
|
|
r.Use(middleware.Logger)
|
|
r.Use(middleware.RealIP)
|
|
r.Use(middleware.CleanPath)
|
|
|
|
r.Route("/api", func(r chi.Router) {
|
|
r.Use(cors.Handler(cors.Options{
|
|
AllowedOrigins: []string{"https://hackathon.teamortix.com", "http://localhost:8081"},
|
|
|
|
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
|
|
AllowedHeaders: []string{"Authorization", "Content-Type", "*"},
|
|
AllowCredentials: true,
|
|
MaxAge: 300,
|
|
}))
|
|
|
|
api.HandlerFromMux(server, r)
|
|
})
|
|
|
|
s := &http.Server{
|
|
Handler: r,
|
|
Addr: fmt.Sprintf("0.0.0.0:%d", *port),
|
|
}
|
|
|
|
log.Println("Starting Web server on", s.Addr)
|
|
return s.ListenAndServe()
|
|
}
|
|
|
|
func main() {
|
|
if err := run(); err != nil {
|
|
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|