reprogl
/
main.go
112 строк · 2.5 Кб
1package main2
3import (4"context"5"errors"6"fmt"7"log"8"net/http"9"os"10"os/signal"11"runtime"12"runtime/debug"13"syscall"14"time"15
16"github.com/xelbot/reverse"17"xelbot.com/reprogl/container"18"xelbot.com/reprogl/middlewares"19"xelbot.com/reprogl/services/oauth"20"xelbot.com/reprogl/views"21)
22
23func main() {24var err error25infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime|log.Lmicroseconds)26errorLog := log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)27
28infoLog.Printf("Version: %s (tag: %s)", container.Version, container.GetBuildTag())29infoLog.Printf("Build time: %s", container.BuildTimeRFC1123())30infoLog.Printf("Go version: %s", runtime.Version())31
32handleError(container.Load("app.ini"), errorLog)33
34app := &container.Application{35ErrorLog: errorLog,36InfoLog: infoLog,37}38
39handleError(app.SetupDatabase(), errorLog)40
41router := getRoutes(app)42handler := middlewares.Session(router, infoLog)43handler = middlewares.Clacks().Middleware(handler)44handler = middlewares.CDN(handler)45handler = middlewares.Recover(handler, app)46handler = middlewares.Track(handler, app)47handler = middlewares.AccessLog(handler, app)48handler = middlewares.ResponseWrapper(handler)49
50cfg := container.GetConfig()51
52urlGenerator := func(routeName string, absoluteURL bool, pairs ...string) string {53var url string54url, err = reverse.Get(routeName, pairs...)55if err != nil {56errorLog.Printf("[urlGenerator] URL generation error for: %s", routeName)57url = "/error"58}59
60var prefix string61if absoluteURL {62prefix = "https://" + cfg.Host63}64
65return prefix + url66}67
68container.SetURLGenerator(urlGenerator)69handleError(views.LoadViewSet(), errorLog)70
71oauth.SetLogger(infoLog)72
73server := &http.Server{74Handler: handler,75Addr: ":" + cfg.Port,76WriteTimeout: 10 * time.Second,77ReadTimeout: 10 * time.Second,78}79
80go func() {81infoLog.Printf("Starting server on %s port", cfg.Port)82err = server.ListenAndServe()83if !errors.Is(err, http.ErrServerClosed) {84handleError(err, errorLog)85}86}()87
88exit := make(chan os.Signal, 1)89signal.Notify(exit, os.Interrupt, syscall.SIGTERM)90
91<-exit92
93infoLog.Print("Shutting down...")94err = server.Shutdown(context.Background())95if err != nil {96errorLog.Fatal(err)97}98infoLog.Print("Server stopped")99
100err = app.Stop()101if err != nil {102errorLog.Fatal(err)103}104infoLog.Print("Application stopped")105}
106
107func handleError(err error, logger *log.Logger) {108if err != nil {109logger.Println(fmt.Sprintf("%s", debug.Stack()))110logger.Fatal(err)111}112}
113