/
runhook.go
62 lines (53 loc) · 1.57 KB
/
runhook.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
// The helloworld-configurable package implements an example
// charm similar to http://godoc.org/github.com/juju/gocharm/example-charms/helloworld
// but which allows the message to be configured, demonstrating how
// changing configuration options can affect a running service.
//
// Once deployed, the message can be changed with:
// juju set helloworld-configurable message='my new message'
package runhook
import (
"fmt"
"net/http"
"gopkg.in/errgo.v1"
"gopkg.in/juju/charm.v6-unstable"
"github.com/juju/gocharm/charmbits/httpservice"
"github.com/juju/gocharm/hook"
)
func RegisterHooks(r *hook.Registry) {
var hw helloWorld
hw.svc.Register(r.Clone("httpservice"), "", "webserver", hw.handler)
r.RegisterHook("config-changed", func() error { return nil })
r.RegisterConfig("message", charm.Option{
Type: "string",
Description: "message to serve",
Default: "hello, world",
})
r.RegisterHook("*", hw.changed)
r.RegisterContext(hw.setContext, nil)
}
type helloWorld struct {
ctxt *hook.Context
svc httpservice.Service
}
func (hw *helloWorld) setContext(ctxt *hook.Context) error {
hw.ctxt = ctxt
return nil
}
func (hw *helloWorld) changed() error {
message, err := hw.ctxt.GetConfigString("message")
if err != nil {
return errgo.Notef(err, "cannot get message from configuration")
}
return hw.svc.Start(¶ms{
Message: message,
})
}
type params struct {
Message string
}
func (hw *helloWorld) handler(p *params) (http.Handler, error) {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, p.Message)
}), nil
}