main.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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.GlobalServerConfig.LoadConfig()
  19. audit.Init(config.GlobalServerConfig.InDevelopment)
  20. template.Init(config.GlobalServerConfig.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. main_handler := func(w http.ResponseWriter, r *http.Request) {
  28. router.ServeHTTP(w, r)
  29. handlers.ErrorHandler(w, r)
  30. }
  31. main_handler = handlers.RateLimitRequest(main_handler)
  32. main_handler = handlers.LogRequest(main_handler)
  33. // run sass when in development mode
  34. if config.GlobalServerConfig.InDevelopment {
  35. go func() {
  36. cmd := exec.Command("sass", "--watch", "assets/css")
  37. cmd.Stdout = os.Stderr // Sass quirk
  38. cmd.Stderr = os.Stderr
  39. cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true, Pdeathsig: syscall.SIGHUP}
  40. runtime.LockOSThread() // Go quirk https://github.com/golang/go/issues/27505
  41. err := cmd.Run()
  42. if err != nil {
  43. log.Print(fmt.Errorf("when running sass: %w", err))
  44. }
  45. }()
  46. }
  47. // Listen
  48. var l net.Listener
  49. if config.GlobalServerConfig.UnixSocket != "" {
  50. ln, err := net.Listen("unix", config.GlobalServerConfig.UnixSocket)
  51. if err != nil {
  52. panic(err)
  53. }
  54. l = ln
  55. log.Printf("Listening on domain socket %v\n", config.GlobalServerConfig.UnixSocket)
  56. } else {
  57. addr := config.GlobalServerConfig.Host + ":" + config.GlobalServerConfig.Port
  58. ln, err := net.Listen("tcp", addr)
  59. if err != nil {
  60. log.Panicf("failed to listen: %v", err)
  61. }
  62. l = ln
  63. addr = ln.Addr().String()
  64. log.Printf("Listening on http://%v/\n", addr)
  65. }
  66. http.Serve(l, http.HandlerFunc(main_handler))
  67. }