main.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package main
  2. import (
  3. "errors"
  4. "flag"
  5. "fmt"
  6. "log"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "bloat/config"
  12. "bloat/renderer"
  13. "bloat/repo"
  14. "bloat/service"
  15. "bloat/util"
  16. )
  17. var (
  18. configFiles = []string{"bloat.conf", "/etc/bloat.conf"}
  19. )
  20. func errExit(err error) {
  21. fmt.Fprintln(os.Stderr, err.Error())
  22. os.Exit(1)
  23. }
  24. func main() {
  25. configFile := flag.String("f", "", "config file")
  26. flag.Parse()
  27. if len(*configFile) > 0 {
  28. configFiles = []string{*configFile}
  29. }
  30. config, err := config.ParseFiles(configFiles)
  31. if err != nil {
  32. errExit(err)
  33. }
  34. if !config.IsValid() {
  35. errExit(errors.New("invalid config"))
  36. }
  37. templatesGlobPattern := filepath.Join(config.TemplatesPath, "*")
  38. renderer, err := renderer.NewRenderer(templatesGlobPattern)
  39. if err != nil {
  40. errExit(err)
  41. }
  42. err = os.Mkdir(config.DatabasePath, 0755)
  43. if err != nil && !os.IsExist(err) {
  44. errExit(err)
  45. }
  46. sessionDBPath := filepath.Join(config.DatabasePath, "session")
  47. sessionDB, err := util.NewDatabse(sessionDBPath)
  48. if err != nil {
  49. errExit(err)
  50. }
  51. appDBPath := filepath.Join(config.DatabasePath, "app")
  52. appDB, err := util.NewDatabse(appDBPath)
  53. if err != nil {
  54. errExit(err)
  55. }
  56. sessionRepo := repo.NewSessionRepo(sessionDB)
  57. appRepo := repo.NewAppRepo(appDB)
  58. customCSS := config.CustomCSS
  59. if len(customCSS) > 0 && !strings.HasPrefix(customCSS, "http://") &&
  60. !strings.HasPrefix(customCSS, "https://") {
  61. customCSS = "/static/" + customCSS
  62. }
  63. var logger *log.Logger
  64. if len(config.LogFile) < 1 {
  65. logger = log.New(os.Stdout, "", log.LstdFlags)
  66. } else {
  67. lf, err := os.OpenFile(config.LogFile,
  68. os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
  69. if err != nil {
  70. errExit(err)
  71. }
  72. defer lf.Close()
  73. logger = log.New(lf, "", log.LstdFlags)
  74. }
  75. s := service.NewService(config.ClientName, config.ClientScope,
  76. config.ClientWebsite, customCSS, config.SingleInstance,
  77. config.PostFormats, renderer, sessionRepo, appRepo)
  78. handler := service.NewHandler(s, logger, config.StaticDirectory)
  79. logger.Println("listening on", config.ListenAddress)
  80. err = http.ListenAndServe(config.ListenAddress, handler)
  81. if err != nil {
  82. errExit(err)
  83. }
  84. }