main.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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/service"
  14. )
  15. var (
  16. configFiles = []string{"bloat.conf", "/etc/bloat.conf"}
  17. )
  18. func errExit(err error) {
  19. fmt.Fprintln(os.Stderr, err.Error())
  20. os.Exit(1)
  21. }
  22. func main() {
  23. configFile := flag.String("f", "", "config file")
  24. flag.Parse()
  25. if len(*configFile) > 0 {
  26. configFiles = []string{*configFile}
  27. }
  28. config, err := config.ParseFiles(configFiles)
  29. if err != nil {
  30. errExit(err)
  31. }
  32. if !config.IsValid() {
  33. errExit(errors.New("invalid config"))
  34. }
  35. templatesGlobPattern := filepath.Join(config.TemplatesPath, "*")
  36. renderer, err := renderer.NewRenderer(templatesGlobPattern)
  37. if err != nil {
  38. errExit(err)
  39. }
  40. customCSS := config.CustomCSS
  41. if len(customCSS) > 0 && !strings.HasPrefix(customCSS, "http://") &&
  42. !strings.HasPrefix(customCSS, "https://") {
  43. customCSS = "/static/" + customCSS
  44. }
  45. var logger *log.Logger
  46. if len(config.LogFile) < 1 {
  47. logger = log.New(os.Stdout, "", log.LstdFlags)
  48. } else {
  49. lf, err := os.OpenFile(config.LogFile,
  50. os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
  51. if err != nil {
  52. errExit(err)
  53. }
  54. defer lf.Close()
  55. logger = log.New(lf, "", log.LstdFlags)
  56. }
  57. s := service.NewService(config.ClientName, config.ClientScope,
  58. config.ClientWebsite, customCSS, config.SingleInstance,
  59. config.PostFormats, renderer)
  60. handler := service.NewHandler(s, logger, config.StaticDirectory)
  61. logger.Println("listening on", config.ListenAddress)
  62. err = http.ListenAndServe(config.ListenAddress, handler)
  63. if err != nil {
  64. errExit(err)
  65. }
  66. }