wordsearch/standalone/main.go

73 lines
1.5 KiB
Go
Raw Permalink Normal View History

2023-10-07 17:12:47 +01:00
package main
import (
"embed"
"encoding/gob"
"flag"
2023-10-07 17:12:47 +01:00
"log"
"net"
2023-10-07 17:12:47 +01:00
"net/http"
"strings"
2023-10-07 17:12:47 +01:00
2023-10-08 15:05:12 +01:00
"github.com/ray1729/wordsearch/anagram"
"github.com/ray1729/wordsearch/match"
"github.com/ray1729/wordsearch/standalone/server"
2023-10-07 17:12:47 +01:00
)
//go:embed data/*
var fs embed.FS
2023-10-07 17:12:47 +01:00
var anagramDB anagram.DB
var matchDB match.DB
2023-10-07 17:12:47 +01:00
func initializeDB() error {
anagrams, err := fs.Open("data/anagram.bin")
2023-10-07 17:12:47 +01:00
if err != nil {
return err
2023-10-07 17:12:47 +01:00
}
defer anagrams.Close()
if err := gob.NewDecoder(anagrams).Decode(&anagramDB); err != nil {
return err
2023-10-07 17:12:47 +01:00
}
matches, err := fs.Open("data/match.bin")
if err != nil {
return err
}
defer matches.Close()
if err := gob.NewDecoder(matches).Decode(&matchDB); err != nil {
return err
}
return nil
}
func init() {
if err := initializeDB(); err != nil {
log.Fatalf("error initializing databases: %v", err)
2023-10-07 17:12:47 +01:00
}
}
func main() {
var listenAddr = flag.String("listen", ":8000", "Address or port to listen on, prefix with unix: to listen on a Unix domain socket")
flag.Parse()
server := http.Server{
Handler: server.New(matchDB, anagramDB),
}
var listener net.Listener
var err error
if strings.HasPrefix(*listenAddr, "unix:") {
listener, err = net.Listen("unix", strings.TrimPrefix(*listenAddr, "unix:"))
} else {
listener, err = net.Listen("tcp", *listenAddr)
}
if err != nil {
log.Fatalf("Error listening on %s: %v", *listenAddr, err)
}
log.Printf("Listening on %s", *listenAddr)
if err := server.Serve(listener); err != nil {
2023-10-07 17:12:47 +01:00
log.Fatal(err)
}
}