autotls icon indicating copy to clipboard operation
autotls copied to clipboard

Question: Example how to use autotls with graceful-shutdown

Open valasek opened this issue 5 years ago • 1 comments

I am using graceful-shutdown and now want to add LetsEncrypt via autotls but struggling how-to

srv := &http.Server{
  Addr:    url + ":" + port,
  Handler: r,
}
srv.ListenAndServe()

vs autotls.Run(routes, domains ...) How this is possible?

valasek avatar Mar 04 '19 20:03 valasek

How to use autotls with graceful-shutdown?

Set address and port and create Server struct

url := "url"
port := "port"
var address = url
if (len(port) > 0) {
  address =  address + ":" + port
}
srv := &http.Server{
  Addr:    address,
  Handler: r,
}

and instead of

if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  fmt.Errorf("listen: %s", err))
}

use

if err := autotls.Run(r, url) ; err != nil && err != http.ErrServerClosed {
  fmt.Errorf("listen: %s", err))
}

An issue can be closed and I propose to update README with this example.

valasek avatar Mar 30 '19 17:03 valasek

example usage for graceful shutdown with custom context.

package main

import (
  "context"
  "log"
  "net/http"
  "os/signal"
  "syscall"

  "github.com/gin-gonic/autotls"
  "github.com/gin-gonic/gin"
)

func main() {
  // Create context that listens for the interrupt signal from the OS.
  ctx, stop := signal.NotifyContext(
    context.Background(),
    syscall.SIGINT,
    syscall.SIGTERM,
  )
  defer stop()

  r := gin.Default()

  // Ping handler
  r.GET("/ping", func(c *gin.Context) {
    c.String(http.StatusOK, "pong")
  })

  log.Fatal(autotls.RunWithContext(ctx, r, "example1.com", "example2.com"))
}

Already updated in README.

appleboy avatar Aug 30 '22 08:08 appleboy