Skip to content

Commit

Permalink
Merge pull request #34 from evanebb/feature/https
Browse files Browse the repository at this point in the history
Add HTTPS support through configuration options
  • Loading branch information
evanebb authored Sep 9, 2023
2 parents ef9a54d + bdf6f7f commit 22f3933
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
25 changes: 24 additions & 1 deletion server/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ type AppConfig struct {
dbHost string
dbName string
dbPort int
httpsEnabled bool
httpsCertFile string
httpsKeyFile string
listenAddress string
}

Expand All @@ -24,7 +27,6 @@ func NewAppConfig() (AppConfig, error) {

// Default values if applicable
a.dbPort = 5432
a.listenAddress = ":80"

// Parse environment variables
a.dbUser = os.Getenv("GOBBLE_DB_USER")
Expand All @@ -39,6 +41,9 @@ func NewAppConfig() (AppConfig, error) {
}
}

a.httpsCertFile = os.Getenv("GOBBLE_HTTPS_CERT_FILE")
a.httpsKeyFile = os.Getenv("GOBBLE_HTTPS_KEY_FILE")

listenAddress := os.Getenv("GOBBLE_LISTEN_ADDRESS")
if listenAddress != "" {
a.listenAddress = listenAddress
Expand All @@ -50,12 +55,30 @@ func NewAppConfig() (AppConfig, error) {
flag.StringVar(&a.dbHost, "db-host", a.dbHost, "the database host")
flag.StringVar(&a.dbName, "db-name", a.dbHost, "the database to use")
flag.IntVar(&a.dbPort, "db-port", a.dbPort, "the database port to connect to")
flag.StringVar(&a.httpsCertFile, "https-cert-file", a.httpsCertFile, "the TLS certificate file to use for HTTPS")
flag.StringVar(&a.httpsKeyFile, "https-key-file", a.httpsKeyFile, "the TLS certificate key file to use for HTTPS")
flag.StringVar(&a.listenAddress, "listen-address", a.listenAddress, "the address that the application should listen on")
flag.Parse()

if a.dbUser == "" || a.dbPass == "" || a.dbHost == "" || a.dbName == "" {
return a, ErrIncompleteDatabaseCredentials
}

// If both a certificate and corresponding key file path have been passed, HTTPS will be enabled
if a.httpsCertFile != "" && a.httpsKeyFile != "" {
a.httpsEnabled = true
} else {
a.httpsEnabled = false
}

// If no listen address has been passed, set an appropriate default depending on whether HTTPS has been enabled
if a.listenAddress == "" {
if a.httpsEnabled {
a.listenAddress = ":443"
} else {
a.listenAddress = ":80"
}
}

return a, nil
}
6 changes: 5 additions & 1 deletion server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,9 @@ func NewServer() (Server, error) {
func (s *Server) Run() {
log.Println("starting API...")
s.routes()
log.Fatal(http.ListenAndServe(s.config.listenAddress, s.router))
if s.config.httpsEnabled {
log.Fatal(http.ListenAndServeTLS(s.config.listenAddress, s.config.httpsCertFile, s.config.httpsKeyFile, s.router))
} else {
log.Fatal(http.ListenAndServe(s.config.listenAddress, s.router))
}
}

0 comments on commit 22f3933

Please sign in to comment.