This repository has been archived on 2020-08-21. You can view files and clone it, but cannot push or open issues or pull requests.
filicop/server/main.go

109 lines
2.3 KiB
Go

package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"path"
"strings"
"syscall"
"git.nemunai.re/filicop/server/api"
"git.nemunai.re/filicop/server/models"
)
type ResponseWriterPrefix struct {
real http.ResponseWriter
prefix string
}
func (r ResponseWriterPrefix) Header() http.Header {
return r.real.Header()
}
func (r ResponseWriterPrefix) WriteHeader(s int) {
if v, exists := r.real.Header()["Location"]; exists {
r.real.Header().Set("Location", r.prefix+v[0])
}
r.real.WriteHeader(s)
}
func (r ResponseWriterPrefix) Write(z []byte) (int, error) {
return r.real.Write(z)
}
func StripPrefix(prefix string, h http.Handler) http.Handler {
if prefix == "" {
return h
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if prefix != "/" && r.URL.Path == "/" {
http.Redirect(w, r, prefix+"/", http.StatusFound)
} else if p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) {
r2 := new(http.Request)
*r2 = *r
r2.URL = new(url.URL)
*r2.URL = *r.URL
r2.URL.Path = p
h.ServeHTTP(ResponseWriterPrefix{w, prefix}, r2)
} else {
h.ServeHTTP(w, r)
}
})
}
func main() {
// Read parameters from command line
var bind = flag.String("bind", "127.0.0.1:8081", "Bind port/socket")
var dsn = flag.String("dsn", filicop.DSNGenerator(), "DSN to connect to the MySQL server")
var baseURL = flag.String("baseurl", "/", "URL prepended to each URL")
flag.Parse()
// Sanitize options
if *baseURL != "/" {
tmp := path.Clean(*baseURL)
baseURL = &tmp
} else {
tmp := ""
baseURL = &tmp
}
log.Println("Opening database...")
if err := filicop.DBInit(*dsn); err != nil {
log.Fatal("Cannot open the database: ", err)
}
defer filicop.DBClose()
log.Println("Creating database...")
if err := filicop.DBCreate(); err != nil {
log.Fatal("Cannot create database: ", err)
}
// Prepare graceful shutdown
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
srv := &http.Server{
Addr: *bind,
Handler: StripPrefix(*baseURL, api.Router()),
}
// Serve content
go func() {
log.Fatal(srv.ListenAndServe())
}()
log.Println(fmt.Sprintf("Ready, listening on %s", *bind))
// Wait shutdown signal
<-interrupt
log.Print("The service is shutting down...")
srv.Shutdown(context.Background())
log.Println("done")
}