package main import ( "errors" "fmt" "log" "github.com/foolin/goview" "github.com/foolin/goview/supports/ginview" "github.com/gin-gonic/gin" flag "github.com/spf13/pflag" ) // WebsiteConfig contains the config to run the server with type WebsiteConfig struct { port uint disableCache bool certFile string keyFile string tls bool publicDir string } func parseWebsiteConfig() (WebsiteConfig, error) { var config WebsiteConfig flag.BoolVar(&config.disableCache, "disable-cache", false, "Disable cache (for testing)") flag.UintVar(&config.port, "port", 8080, "port to listen and serve on") flag.StringVar(&config.certFile, "cert-file", "", "location of certificate file (TLS)") flag.StringVar(&config.keyFile, "key-file", "", "location of the key file (TLS)") flag.StringVar(&config.publicDir, "public-dir", "./public", "location of the directory to be served") var proxiesvar []string flag.StringArrayVarP(&proxiesvar, "proxy", "", []string{}, "define a hostname reverse proxy") flag.Parse() if config.certFile != "" { if config.keyFile == "" { return config, errors.New("TLS: Certificate file provided without key file") } config.tls = true } else if config.keyFile != "" { return config, errors.New("TLS: Key file provided without certificate file") } if config.port == 0 || config.port > 65535 { log.Fatal("Invalid port number: ", config.port) return config, errors.New("Invalid port number:" + fmt.Sprintf("%d", config.port)) } return config, nil } func setupRouter(config WebsiteConfig) (*gin.Engine, error) { fmt.Println("Using port ", config.port) fmt.Println("Disable cache: ", config.disableCache) fmt.Println("Using TLS: ", config.tls) fmt.Println("Public directory: ", config.publicDir) router := gin.Default() ginviewConfig := goview.DefaultConfig if config.disableCache { fmt.Println("Disabling cache...") ginviewConfig.DisableCache = true } router.HTMLRender = ginview.New(ginviewConfig) router.Static("/", config.publicDir) router.SetTrustedProxies(nil) return router, nil } func main() { config, err := parseWebsiteConfig() if err != nil { log.Fatal("Error: ", err) } r, err := setupRouter(config) if err != nil { log.Fatal("Error: ", err) } // Listen and Server on specified port if config.tls { err = r.RunTLS(":"+fmt.Sprintf("%d", config.port), config.certFile, config.keyFile) if err != nil { log.Fatal("Error running the server with TLS: ", err) } } else { err = r.Run(":" + fmt.Sprintf("%d", config.port)) if err != nil { log.Fatal("Error running the server (http): ", err) } } }