Skip to content

Commit 7e8ed2f

Browse files
authored
Merge pull request #563 from devlights/add-http-example
2 parents 6f032e9 + ddc3298 commit 7e8ed2f

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
version: '3'
2+
3+
tasks:
4+
run:
5+
cmds:
6+
- go run -race main.go

examples/http/shutdown/main.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"log"
6+
"net/http"
7+
"time"
8+
)
9+
10+
func main() {
11+
var (
12+
mux = http.NewServeMux()
13+
srv = &http.Server{Addr: ":8888", Handler: mux}
14+
mainCtx = context.Background()
15+
procCtx, procCxl = context.WithTimeout(mainCtx, 3*time.Second)
16+
)
17+
defer procCxl()
18+
19+
// ----------- Start ----------- //
20+
21+
go func() {
22+
log.Println("Server is up.")
23+
srv.ListenAndServe()
24+
}()
25+
26+
<-procCtx.Done()
27+
28+
// ----------- Shutdown ----------- //
29+
30+
var (
31+
shutdownCtx, shutdownCxl = context.WithTimeout(mainCtx, 1*time.Second)
32+
)
33+
defer shutdownCxl()
34+
35+
if err := srv.Shutdown(shutdownCtx); err != nil {
36+
switch err {
37+
case context.DeadlineExceeded:
38+
log.Println("Server shutdown process timed out.")
39+
default:
40+
log.Fatal(err)
41+
}
42+
}
43+
log.Println("Server has been shutdown.")
44+
}

0 commit comments

Comments
 (0)