library/cmd/serve/main.go

91 lines
2.0 KiB
Go
Raw Normal View History

2021-06-26 18:08:35 +00:00
package main
import (
2021-07-02 22:13:58 +00:00
"context"
"encoding/json"
2021-06-26 18:08:35 +00:00
"io/fs"
2021-07-02 22:13:58 +00:00
"log"
2021-06-26 18:08:35 +00:00
"net/http"
2021-07-02 22:13:58 +00:00
"git.yetaga.in/alazyreader/library/book"
2021-07-03 00:46:58 +00:00
"git.yetaga.in/alazyreader/library/config"
2021-07-02 22:13:58 +00:00
"git.yetaga.in/alazyreader/library/database"
2021-06-26 18:08:35 +00:00
"git.yetaga.in/alazyreader/library/frontend"
2021-07-02 22:47:14 +00:00
"github.com/kelseyhightower/envconfig"
2021-06-26 18:08:35 +00:00
)
2021-07-02 22:13:58 +00:00
type Library interface {
GetAllBooks(context.Context) ([]book.Book, error)
}
type Router struct {
static fs.FS
lib Library
}
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/api" {
APIHandler(r.lib).ServeHTTP(w, req)
return
}
StaticHandler(r.static).ServeHTTP(w, req)
return
}
func APIHandler(l Library) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
books, err := l.GetAllBooks(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
b, err := json.Marshal(books)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(b)
w.Write([]byte("\n"))
})
}
func StaticHandler(f fs.FS) http.Handler {
return http.FileServer(http.FS(f))
}
2021-06-26 18:08:35 +00:00
func main() {
2021-07-03 00:46:58 +00:00
var c config.Config
2021-07-02 22:47:14 +00:00
err := envconfig.Process("library", &c)
if err != nil {
log.Fatalln(err)
}
2021-07-02 22:13:58 +00:00
f, err := frontend.Root()
if err != nil {
log.Fatalln(err)
}
2021-07-02 22:47:14 +00:00
if c.DBUser == "" || c.DBPass == "" || c.DBHost == "" || c.DBPort == "" || c.DBName == "" {
log.Fatalf("vars: %+v", c)
}
lib, err := database.NewMySQLConnection(c.DBUser, c.DBPass, c.DBHost, c.DBPort, c.DBName)
2021-07-02 22:13:58 +00:00
if err != nil {
log.Fatalln(err)
}
err = lib.PrepareDatabase(context.Background())
if err != nil {
log.Fatalln(err)
}
latest, run, err := lib.RunMigrations(context.Background())
if err != nil {
log.Fatalln(err)
}
log.Printf("latest migration: %d; migrations run: %d", latest, run)
r := &Router{
static: f,
lib: lib,
}
log.Println("Listening on http://localhost:8080/")
log.Fatalln(http.ListenAndServe(":8080", r))
2021-06-26 18:08:35 +00:00
}