Listen on custom address (#140)

Co-Authored-By: eternal-flame-AD <ef@eternalflame.info>
This commit is contained in:
饺子w 2019-03-08 16:40:26 +08:00 committed by Jannis Mattheis
parent 1a4707acc4
commit d82a78b8aa
3 changed files with 12 additions and 6 deletions

View File

@ -2,11 +2,13 @@
# Save it to `config.yml` when edited
server:
listenaddr: "" # the address to bind on, leave empty to bind on all addresses
port: 80 # the port the HTTP server will listen on
ssl:
enabled: false # if https should be enabled
redirecttohttps: true # redirect to https if site is accessed by http
listenaddr: "" # the address to bind on, leave empty to bind on all addresses
port: 443 # the https port
certfile: # the cert file (leave empty when using letsencrypt)
certkey: # the cert key (leave empty when using letsencrypt)

View File

@ -10,10 +10,12 @@ import (
// Configuration is stuff that can be configured externally per env variables or config file (config.yml).
type Configuration struct {
Server struct {
Port int `default:"80"`
SSL struct {
ListenAddr string `default:""`
Port int `default:"80"`
SSL struct {
Enabled *bool `default:"false"`
RedirectToHTTPS *bool `default:"true"`
ListenAddr string `default:""`
Port int `default:"443"`
CertFile string `default:""`
CertKey string `default:""`

View File

@ -21,8 +21,9 @@ func Run(engine *gin.Engine, conf *config.Configuration) {
httpHandler = redirectToHTTPS(string(conf.Server.SSL.Port))
}
addr := fmt.Sprintf("%s:%d", conf.Server.SSL.ListenAddr, conf.Server.SSL.Port)
s := &http.Server{
Addr: fmt.Sprintf(":%d", conf.Server.SSL.Port),
Addr: addr,
Handler: engine,
}
@ -35,13 +36,14 @@ func Run(engine *gin.Engine, conf *config.Configuration) {
httpHandler = certManager.HTTPHandler(httpHandler)
s.TLSConfig = &tls.Config{GetCertificate: certManager.GetCertificate}
}
fmt.Println("Started Listening on port", conf.Server.SSL.Port)
fmt.Println("Started Listening for TLS connection on " + addr)
go func() {
log.Fatal(s.ListenAndServeTLS(conf.Server.SSL.CertFile, conf.Server.SSL.CertKey))
}()
}
fmt.Println("Started Listening on port", conf.Server.Port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", conf.Server.Port), httpHandler))
addr := fmt.Sprintf("%s:%d", conf.Server.ListenAddr, conf.Server.Port)
fmt.Println("Started Listening for plain HTTP connection on " + addr)
log.Fatal(http.ListenAndServe(addr, httpHandler))
}
func redirectToHTTPS(port string) http.HandlerFunc {