Skip to content

Commit

Permalink
refactor: refactor error handling and improve code readability
Browse files Browse the repository at this point in the history
- Remove unused import of `log`
- Refactor cache initialization to handle errors and return them if cache directory cannot be obtained
- Add spacing for better readability in the `RunWithManagerAndTLSConfig` function

Signed-off-by: appleboy <[email protected]>
  • Loading branch information
appleboy committed Dec 27, 2024
1 parent 94aedbd commit 561a32f
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions autotls.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package autotls
import (
"context"
"crypto/tls"
"log"
"net/http"
"time"

Expand Down Expand Up @@ -77,22 +76,26 @@ func RunWithManager(r http.Handler, m *autocert.Manager) error {
// RunWithManagerAndTLSConfig support custom autocert manager and tls.Config
func RunWithManagerAndTLSConfig(r http.Handler, m *autocert.Manager, tlsc *tls.Config) error {
var g errgroup.Group

if m.Cache == nil {
var e error
m.Cache, e = getCacheDir()
if e != nil {
log.Println(e)
cache, err := getCacheDir()
if err != nil {
return err
}
m.Cache = cache
}

defaultTLSConfig := m.TLSConfig()
tlsc.GetCertificate = defaultTLSConfig.GetCertificate
tlsc.NextProtos = defaultTLSConfig.NextProtos

s := &http.Server{
Addr: ":https",
TLSConfig: tlsc,
Handler: r,
ReadHeaderTimeout: ReadHeaderTimeout,
}

g.Go(func() error {
s := &http.Server{
Addr: ":http",
Expand All @@ -101,14 +104,15 @@ func RunWithManagerAndTLSConfig(r http.Handler, m *autocert.Manager, tlsc *tls.C
}
return s.ListenAndServe()
})

g.Go(func() error {
return s.ListenAndServeTLS("", "")
})

return g.Wait()
}

func redirect(w http.ResponseWriter, req *http.Request) {
target := "https://" + req.Host + req.RequestURI

http.Redirect(w, req, target, http.StatusMovedPermanently)
}

0 comments on commit 561a32f

Please sign in to comment.