Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 14, 05:15 UTC
move internal packages to pkg folder and update reverse proxy
* set automatic https error type for cert-magic failures * add state to onload and unload methods * update reverse proxy to use Provision() and Cleanup()
dev committed
May 14, 2019 at 10:35 UTC
043eb1d9e5db456b9b78c0423cb44716fc81a932
12 files changed
+65
-24
cmd/caddy2/main.go
-1
@@ -4,7 +4,6 @@ import (
4
caddycmd "bitbucket.org/lightcodelabs/caddy2/cmd"
5
6
// this is where modules get plugged in
7
-
7
_ "bitbucket.org/lightcodelabs/caddy2/modules/caddyhttp"
8
_ "bitbucket.org/lightcodelabs/caddy2/modules/caddyhttp/caddylog"
9
_ "bitbucket.org/lightcodelabs/caddy2/modules/caddyhttp/reverseproxy"
context.go
+1
@@ -39,6 +39,7 @@ func NewContext(ctx Context) (Context, context.CancelFunc) {
39
c, cancel := context.WithCancel(ctx.Context)
40
wrappedCancel := func() {
41
cancel()
42
+
43
for modName, modInstances := range newCtx.moduleInstances {
44
for _, inst := range modInstances {
45
if cu, ok := inst.(CleanerUpper); ok {
go.mod
+1
@@ -6,6 +6,7 @@ require (
6
github.com/go-acme/lego v2.5.0+incompatible
7
github.com/klauspost/cpuid v1.2.1
8
github.com/mholt/certmagic v0.5.1
9
+ github.com/starlight-go/starlight v0.0.0-20181207205707-b06f321544f3
10
go.starlark.net v0.0.0-20190506145734-95b2783e7d63
11
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c
12
)
go.sum
+2
@@ -11,6 +11,8 @@ github.com/mholt/certmagic v0.5.1/go.mod h1:g4cOPxcjV0oFq3qwpjSA30LReKD8AoIfwAY9
11
github.com/miekg/dns v1.1.3 h1:1g0r1IvskvgL8rR+AcHzUA+oFmGcQlaIm4IqakufeMM=
12
github.com/miekg/dns v1.1.3/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
13
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
14
+github.com/starlight-go/starlight v0.0.0-20181207205707-b06f321544f3 h1:/fBh1Ot84ILt/ociFHO98wJ9LxIMA3UG8B0unUJPFpY=
15
+github.com/starlight-go/starlight v0.0.0-20181207205707-b06f321544f3/go.mod h1:pxOc2ZuBV+CNlQgzq/HJ9Z9G/eoEMHFeuGohOvva4Co=
16
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
17
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
18
go.starlark.net v0.0.0-20190506145734-95b2783e7d63 h1:WVWIwnUjRw+Tf2iLM4GbAKbSteS4EOhS3z5qXOXN3Vk=
internal/caddyscript/lib/lib.go
deleted
-11
@@ -1,11 +0,0 @@
1
-package caddyscript
2
-
3
-import (
4
- "fmt"
5
-
6
- "go.starlark.net/starlark"
7
-)
8
-
9
-func invalidReciever(v starlark.Value, want string) (starlark.Value, error) {
10
- return starlark.None, fmt.Errorf("invalid receiver: receiver set to type %v, want %v", v.Type(), want)
11
-}
modules/caddyhttp/caddyhttp.go
+12
-1
@@ -24,6 +24,7 @@ func init() {
24
Name: "http",
25
New: func() (interface{}, error) { return new(App), nil },
26
})
27
+
28
if err != nil {
29
log.Fatal(err)
30
}
@@ -94,11 +95,21 @@ func (app *App) Validate() error {
95
return nil
96
}
97
98
+// AutomaticHTTPSError represents an error received when attempting to enable automatic https.
99
+type AutomaticHTTPSError struct {
100
+ internal error
101
+}
102
+
103
+// Error returns the error string for automaticHTTPSError.
104
+func (a AutomaticHTTPSError) Error() string {
105
+ return fmt.Sprintf("enabling automatic HTTPS: %v", a.internal.Error())
106
+}
107
+
108
// Start runs the app. It sets up automatic HTTPS if enabled.
109
func (app *App) Start() error {
110
err := app.automaticHTTPS()
111
if err != nil {
101
- return fmt.Errorf("enabling automatic HTTPS: %v", err)
112
+ return &AutomaticHTTPSError{internal: err}
113
}
114
115
for srvName, srv := range app.Servers {
modules/caddyhttp/matchers.go
+1
-1
@@ -12,7 +12,7 @@ import (
12
"strings"
13
14
"bitbucket.org/lightcodelabs/caddy2"
15
- "bitbucket.org/lightcodelabs/caddy2/internal/caddyscript"
15
+ "bitbucket.org/lightcodelabs/caddy2/pkg/caddyscript"
16
"go.starlark.net/starlark"
17
)
18
modules/caddyhttp/reverseproxy/upstream.go
+21
-8
@@ -17,12 +17,6 @@ import (
17
"bitbucket.org/lightcodelabs/caddy2"
18
)
19
20
-// State represents the global state of a loadbalancer. It is used to store
21
-// references to health checkers.
22
-type State struct {
23
- HealthCheckers []*HealthChecker
24
-}
25
-
20
// CircuitBreaker defines the functionality of a circuit breaker module.
21
type CircuitBreaker interface {
22
Ok() bool
@@ -76,7 +70,7 @@ var (
70
)
71
72
// NewLoadBalancedReverseProxy returns a collection of Upstreams that are to be loadbalanced.
79
-func NewLoadBalancedReverseProxy(lb *LoadBalanced, state *State, ctx caddy2.Context) error {
73
+func NewLoadBalancedReverseProxy(lb *LoadBalanced, ctx caddy2.Context) error {
74
// set defaults
75
if lb.NoHealthyUpstreamsMessage == "" {
76
lb.NoHealthyUpstreamsMessage = msgNoHealthyUpstreams
@@ -145,7 +139,7 @@ func NewLoadBalancedReverseProxy(lb *LoadBalanced, state *State, ctx caddy2.Cont
139
// nu.Target.Path = uc.HealthCheckPath
140
141
go nu.healthChecker.ScheduleChecks(nu.Target.String())
148
- state.HealthCheckers = append(state.HealthCheckers, nu.healthChecker)
142
+ lb.HealthCheckers = append(lb.HealthCheckers, nu.healthChecker)
143
144
us = append(us, nu)
145
}
@@ -178,6 +172,25 @@ type LoadBalanced struct {
172
173
// NoHealthyUpstreamsMessage is returned as a response when there are no healthy upstreams to loadbalance to.
174
NoHealthyUpstreamsMessage string `json:"no_healthy_upstreams_message"`
175
+
176
+ // TODO :- store healthcheckers as package level state where each upstream gets a single healthchecker
177
+ // currently a healthchecker is created for each upstream defined, even if a healthchecker was previously created
178
+ // for that upstream
179
+ HealthCheckers []*HealthChecker
180
+}
181
+
182
+// Cleanup stops all health checkers on a loadbalanced reverse proxy.
183
+func (lb *LoadBalanced) Cleanup() error {
184
+ for _, hc := range lb.HealthCheckers {
185
+ hc.Stop()
186
+ }
187
+
188
+ return nil
189
+}
190
+
191
+// Provision sets up a new loadbalanced reverse proxy.
192
+func (lb *LoadBalanced) Provision(ctx caddy2.Context) error {
193
+ return NewLoadBalancedReverseProxy(lb, ctx)
194
}
195
196
// ServeHTTP implements the http.Handler interface to dispatch an http request to the proper
pkg/caddyscript/lib/http.go
renamed
+26
-1
@@ -4,6 +4,7 @@ import (
4
"fmt"
5
"net/http"
6
7
+ "github.com/starlight-go/starlight/convert"
8
"go.starlark.net/starlark"
9
)
10
@@ -12,7 +13,7 @@ type HTTPRequest struct{ Req *http.Request }
13
14
// AttrNames defines what properties and methods are available on the HTTPRequest type.
15
func (r HTTPRequest) AttrNames() []string {
15
- return []string{"header", "query", "url", "method", "host", "tls"}
16
+ return []string{"header", "query", "url", "method", "host", "tls", "redirect"}
17
}
18
19
func (r HTTPRequest) Freeze() {}
@@ -32,9 +33,33 @@ func (r HTTPRequest) Header(thread *starlark.Thread, fn *starlark.Builtin, args
33
return starlark.String(r.Req.Header.Get(key)), nil
34
}
35
36
+// Redirect handles an http redirect from starlark code.
37
+func (r HTTPRequest) Redirect(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
38
+ var w starlark.Value
39
+ var req HTTPRequest
40
+ var newURL string
41
+ err := starlark.UnpackPositionalArgs(fn.Name(), args, kwargs, 3, &w, &req, &newURL)
42
+ if err != nil {
43
+ return starlark.None, fmt.Errorf("unpacking arguments: %v", err.Error())
44
+ }
45
+
46
+ writer := convert.FromValue(w)
47
+ if w, ok := writer.(http.ResponseWriter); ok {
48
+ http.Redirect(w, req.Req, newURL, http.StatusSeeOther)
49
+ return starlark.None, nil
50
+ }
51
+
52
+ return starlark.None, fmt.Errorf("first provided argument is not http.ResponseWriter")
53
+}
54
+
55
// Attr defines what happens when props or methods are called on the HTTPRequest type.
56
func (r HTTPRequest) Attr(name string) (starlark.Value, error) {
57
switch name {
58
+ case "redirect":
59
+ b := starlark.NewBuiltin("Redirect", r.Redirect)
60
+ b = b.BindReceiver(r)
61
+
62
+ return b, nil
63
case "tls":
64
tls := new(starlark.Dict)
65
tls.SetKey(starlark.String("cipher_suite"), starlark.MakeUint(uint(r.Req.TLS.CipherSuite)))
pkg/caddyscript/lib/regex.go
renamed
pkg/caddyscript/lib/time.go
renamed
pkg/caddyscript/matcherenv.go
renamed
+1
-1
@@ -3,7 +3,7 @@ package caddyscript
3
import (
4
"net/http"
5
6
- caddyscript "bitbucket.org/lightcodelabs/caddy2/internal/caddyscript/lib"
6
+ caddyscript "bitbucket.org/lightcodelabs/caddy2/pkg/caddyscript/lib"
7
"go.starlark.net/starlark"
8
)
9