You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Go 1.8 introduced the ability to [gracefully shutdown](https://golang.org/doc/go1.8#http_shutdown) a `*http.Server`. Here's how to do that alongside `mux`:
390
+
391
+
```go
392
+
package main
393
+
394
+
import (
395
+
"context"
396
+
"flag"
397
+
"log"
398
+
"net/http"
399
+
"os"
400
+
"os/signal"
401
+
402
+
"github.com/gorilla/mux"
403
+
)
404
+
405
+
funcmain() {
406
+
varwait time.Duration
407
+
flag.DurationVar(&wait, "graceful-timeout", time.Second * 15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")
408
+
flag.Parse()
409
+
410
+
r:= mux.NewRouter()
411
+
// Add your routes as needed
412
+
413
+
srv:= &http.Server{
414
+
Addr: "0.0.0.0:8080",
415
+
// Good practice to set timeouts to avoid Slowloris attacks.
416
+
WriteTimeout: time.Second * 15,
417
+
ReadTimeout: time.Second * 15,
418
+
IdleTimeout: time.Second * 60,
419
+
Handler: r, // Pass our instance of gorilla/mux in.
420
+
}
421
+
422
+
// Run our server in a goroutine so that it doesn't block.
423
+
gofunc() {
424
+
iferr:= srv.ListenAndServe(); err != nil {
425
+
log.Println(err)
426
+
}
427
+
}()
428
+
429
+
c:=make(chan os.Signal, 1)
430
+
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
431
+
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
432
+
signal.Notify(c, os.Interrupt)
433
+
434
+
// Block until we receive our signal.
435
+
<-c
436
+
437
+
// Create a deadline to wait for.
438
+
ctx, cancel:= context.WithTimeout(ctx, wait)
439
+
// Doesn't block if no connections, but will otherwise wait
440
+
// until the timeout deadline.
441
+
srv.Shutdown(ctx)
442
+
// Optionally, you could run srv.Shutdown in a goroutine and block on
443
+
// <-ctx.Done() if your application should wait for other services
444
+
// to finalize based on context cancellation.
445
+
log.Println("shutting down")
446
+
os.Exit(0)
447
+
}
448
+
```
449
+
386
450
## Full Example
387
451
388
452
Here's a complete, runnable example of a small `mux` based server:
@@ -391,22 +455,22 @@ Here's a complete, runnable example of a small `mux` based server:
391
455
package main
392
456
393
457
import (
394
-
"net/http"
395
-
"log"
396
-
"github.com/gorilla/mux"
458
+
"net/http"
459
+
"log"
460
+
"github.com/gorilla/mux"
397
461
)
398
462
399
463
funcYourHandler(whttp.ResponseWriter, r *http.Request) {
400
-
w.Write([]byte("Gorilla!\n"))
464
+
w.Write([]byte("Gorilla!\n"))
401
465
}
402
466
403
467
funcmain() {
404
-
r:= mux.NewRouter()
405
-
// Routes consist of a path and a handler function.
406
-
r.HandleFunc("/", YourHandler)
468
+
r:= mux.NewRouter()
469
+
// Routes consist of a path and a handler function.
0 commit comments