-
-
Notifications
You must be signed in to change notification settings - Fork 178
/
main.go
88 lines (74 loc) · 2.36 KB
/
main.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
/*
Package main is a proxy + accesslog example.
In this example we will make a small proxy which listens requests on "/proxy/+path".
With two accesslog instances, one for the main application and one for the /proxy/ requests.
Of cource, you could a single accesslog for the whole application, but for the sake of the example
let's log them separately.
We will make use of iris.StripPrefix and host.ProxyHandler.
*/
package main
import (
"net/url"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/core/host"
"github.com/kataras/iris/v12/middleware/accesslog"
"github.com/kataras/iris/v12/middleware/recover"
)
func main() {
app := iris.New()
app.Get("/", index)
ac := accesslog.File("access.log")
defer ac.Close()
ac.Async = true
ac.RequestBody = true
ac.ResponseBody = true
ac.BytesReceived = false
ac.BytesSent = false
app.UseRouter(ac.Handler)
app.UseRouter(recover.New())
proxy := app.Party("/proxy")
{
acProxy := accesslog.File("proxy_access.log")
defer acProxy.Close()
acProxy.Async = true
acProxy.RequestBody = true
acProxy.ResponseBody = true
acProxy.BytesReceived = false
acProxy.BytesSent = false
// Unlike Use, the UseRouter method replaces any duplications automatically.
// (see UseOnce for the same behavior on Use).
// Therefore, this statement removes the parent's accesslog and registers this new one.
proxy.UseRouter(acProxy.Handler)
proxy.UseRouter(recover.New())
proxy.Use(func(ctx iris.Context) {
ctx.CompressReader(true)
ctx.Next()
})
/* Listen for specific proxy paths:
// Listen on "/proxy" for "http://localhost:9090/read-write"
proxy.Any("/", iris.StripPrefix("/proxy",
newProxyHandler("http://localhost:9090/read-write")))
*/
// You can register an access log only for proxied requests, e.g. proxy_access.log:
// proxy.UseRouter(ac2.Handler)
// Listen for any proxy path.
// Proxies the "/proxy/+$path" to "http://localhost:9090/$path".
proxy.Any("/{p:path}", iris.StripPrefix("/proxy",
newProxyHandler("http://localhost:9090")))
}
// $ go run target/main.go
// open new terminal
// $ go run main.go
app.Listen(":8080")
}
func index(ctx iris.Context) {
ctx.WriteString("OK")
}
func newProxyHandler(proxyURL string) iris.Handler {
target, err := url.Parse(proxyURL)
if err != nil {
panic(err)
}
reverseProxy := host.ProxyHandler(target, nil)
return iris.FromStd(reverseProxy)
}