-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.go
98 lines (81 loc) · 1.8 KB
/
example.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// +build ignore
// Warning: this is old diamond api and will be removed soon.
// Consider changing import paths to gopkg.in or using go modules to stay on v0.2.0 or below
package main
import (
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
diamond "github.com/aerth/diamond/lib"
)
func catchSignals(s *diamond.System) {
go func(srv *diamond.System) {
c := make(chan os.Signal)
signal.Notify(c, syscall.SIGINT, syscall.SIGHUP, syscall.SIGQUIT)
select {
case s := <-c:
println("caught signal:", s.String())
srv.Runlevel(0)
os.Exit(0)
}
}(s)
}
func runlevel0() error {
fmt.Println(time.Now(), "demo runlevel 0\ngoodbye!")
go func() {
<-time.After(time.Second)
os.Exit(0)
}()
return nil
}
func runlevel1() error {
fmt.Println(time.Now(), "demo runlevel 1")
return nil
}
// example type with unexported method 'runlevel3'
type bar struct {
created time.Time
}
var foo = bar{
created: time.Now(),
}
func (b bar) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
}
// yes, runlevel can be a method!
func (b bar) runlevel3() error {
fmt.Println(time.Now(), "demo runlevel 3")
fmt.Println("foo was created at", b.created)
return nil
}
func main() {
// create
srv, err := diamond.New("diamond.socket")
if err != nil {
println(err.Error())
os.Exit(111)
}
// setup
catchSignals(srv)
srv.Config.Verbose = true
srv.Config.Kickable = true
srv.SetRunlevel(0, runlevel0)
srv.SetRunlevel(1, runlevel1)
srv.SetRunlevel(3, foo.runlevel3)
// Add listeners
// Listen on TCP port 2000 on 127.0.0.1
srv.AddListener("tcp", "127.0.0.1:2000")
srv.AddListener("unix", "sample.socket")
srv.SetHandler(foo)
// begin
err = srv.Runlevel(1)
if err != nil {
println(err.Error())
os.Exit(111)
}
// wait (or do stuff)
srv.Wait() // wait until runlevel 0
}