From d82a78b8aa422cfb4370152909844aa01ec471a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A5=BA=E5=AD=90w?= Date: Fri, 8 Mar 2019 16:40:26 +0800 Subject: [PATCH] Listen on custom address (#140) Co-Authored-By: eternal-flame-AD --- config.example.yml | 2 ++ config/config.go | 6 ++++-- runner/runner.go | 10 ++++++---- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/config.example.yml b/config.example.yml index 6fb25457..681e62ee 100644 --- a/config.example.yml +++ b/config.example.yml @@ -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) diff --git a/config/config.go b/config/config.go index 4dc071b7..2e307c3d 100644 --- a/config/config.go +++ b/config/config.go @@ -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:""` diff --git a/runner/runner.go b/runner/runner.go index aa8348ba..3e5cd6f5 100644 --- a/runner/runner.go +++ b/runner/runner.go @@ -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 {