hackathon/cmd/srv/main.go

88 lines
2.1 KiB
Go

package main
import (
"flag"
"fmt"
"io"
"log"
"net"
"os"
"time"
"github.com/hhhapz/codequest/api"
"github.com/hhhapz/codequest/db"
"github.com/hhhapz/codequest/models"
"github.com/peterbourgon/ff/v3"
"google.golang.org/grpc/grpclog"
// questions
_ "github.com/hhhapz/codequest/question/q01"
_ "github.com/hhhapz/codequest/question/q02"
_ "github.com/hhhapz/codequest/question/q03"
)
func run() error {
fs := flag.NewFlagSet("codequest", flag.ExitOnError)
port := fs.Int("port", 10000, "GRPC Server Port")
secretFile := fs.String("secret", "client.secret.json", "Path to google oauth2 secret credentials JSON file.")
redirect := fs.String("redirect", "http://playcode.quest/authorize", "redirect uri")
dbFile := fs.String("db", "db.sqlite", "Path to sqlite3 database file")
debug := fs.Bool("debug", false, "debug sql queries")
start := fs.Int64("start", -1, "competition start time")
end := fs.Int64("end", -1, "competition start time")
if err := ff.Parse(fs, os.Args[1:], ff.WithEnvVarPrefix("CQ")); err != nil {
return err
}
api.Start = time.Unix(*start, 0)
api.End = time.Unix(*end, 0)
fmt.Println("start:", api.Start)
fmt.Println("end:", api.End)
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)
}
if *debug {
models.SetLogger(log.Printf)
}
oaStore, err := db.NewOAuthState(*secretFile, *redirect)
if err != nil {
return fmt.Errorf("could not create oauth config: %w", err)
}
cdStore := db.NewCooldowns()
server, err := api.NewServer(oaStore, database, database, cdStore)
if err != nil {
return fmt.Errorf("could not create server: %w", err)
}
log := grpclog.NewLoggerV2(os.Stderr, io.Discard, os.Stderr)
grpclog.SetLoggerV2(log)
addr := fmt.Sprintf("0.0.0.0:%d", *port)
lis, err := net.Listen("tcp", addr)
if err != nil {
return fmt.Errorf("failed to listen: %v", err)
}
log.Info("Serving gRPC on http://", addr)
return server.Serve(lis)
}
func main() {
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}