main.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "net"
  7. "net/http"
  8. "os"
  9. "os/exec"
  10. "runtime"
  11. "syscall"
  12. "codeberg.org/vnpower/pixivfe/v2/audit"
  13. "codeberg.org/vnpower/pixivfe/v2/config"
  14. "codeberg.org/vnpower/pixivfe/v2/handlers"
  15. "codeberg.org/vnpower/pixivfe/v2/template"
  16. )
  17. func main() {
  18. config.GlobalConfig.LoadConfig()
  19. audit.Init(config.GlobalConfig.InDevelopment)
  20. template.Init(config.GlobalConfig.InDevelopment)
  21. // Initialize and start the proxy checker
  22. ctx_timeout, cancel := context.WithTimeout(context.Background(), config.ProxyCheckerTimeout)
  23. defer cancel()
  24. config.InitializeProxyChecker(ctx_timeout)
  25. handlers.InitializeRateLimiter()
  26. router := handlers.DefineRoutes()
  27. // the first middleware is the most outer / first executed one
  28. router.Use(handlers.ProvideUserContext) // needed for everything else
  29. router.Use(handlers.LogRequest) // all pages need this
  30. router.Use(handlers.SetPrivacyHeaders) // all pages need this
  31. router.Use(handlers.HandleError) // if the inner handler fails, this shows the error page instead
  32. router.Use(handlers.RateLimitRequest)
  33. // watch and compile sass when in development mode
  34. if config.GlobalConfig.InDevelopment {
  35. go run_sass()
  36. }
  37. // Listen
  38. err := http.Serve(chooseListener(), router)
  39. if err != http.ErrServerClosed {
  40. log.Print(err)
  41. }
  42. }
  43. func run_sass() {
  44. cmd := exec.Command("sass", "--watch", "assets/css")
  45. cmd.Stdout = os.Stderr // Sass quirk
  46. cmd.Stderr = os.Stderr
  47. cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true, Pdeathsig: syscall.SIGHUP}
  48. runtime.LockOSThread() // Go quirk https://github.com/golang/go/issues/27505
  49. err := cmd.Run()
  50. if err != nil {
  51. log.Print(fmt.Errorf("when running sass: %w", err))
  52. }
  53. }
  54. func chooseListener() net.Listener {
  55. var l net.Listener
  56. if config.GlobalConfig.UnixSocket != "" {
  57. ln, err := net.Listen("unix", config.GlobalConfig.UnixSocket)
  58. if err != nil {
  59. panic(err)
  60. }
  61. l = ln
  62. log.Printf("Listening on domain socket %v\n", config.GlobalConfig.UnixSocket)
  63. } else {
  64. addr := config.GlobalConfig.Host + ":" + config.GlobalConfig.Port
  65. ln, err := net.Listen("tcp", addr)
  66. if err != nil {
  67. log.Panicf("failed to listen: %v", err)
  68. }
  69. l = ln
  70. addr = ln.Addr().String()
  71. log.Printf("Listening on http://%v/\n", addr)
  72. }
  73. return l
  74. }