-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.go
87 lines (76 loc) · 2.5 KB
/
proxy.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
package main
import (
"fmt"
"net/http"
)
/*
The proxy pattern is a structural design pattern
that enables you to provide a substitute for an object or its placeholder.
The proxy controls access to the original object and allows some processing before and after submitting the request to the object.
1. Lazy initialization (virtual proxy).
2. Access control(protect proxy)
3. Execute the remote service locally (remote proxy).
A web server like Nginx acts as a proxy for the application server
*/
var (
urlStatus = "/system/status"
urlCreate = "/system/create"
resultOK = "ok"
resultNotOK = "not ok"
resultNotAllowed = "not allowed"
resultCreated = "system created"
)
type pServer interface {
handlerRequest(string, string) (int, string)
}
type nginx struct {
application *application
maxAllowedRequest int
rateLimiter map[string]int
}
func newNginxServer() *nginx {
return &nginx{
application: &application{},
maxAllowedRequest: 2,
rateLimiter: make(map[string]int),
}
}
func (n *nginx) handlerRequest(url, method string) (int, string) {
if !n.allowRateLimiting(url) {
return http.StatusForbidden, resultNotAllowed
}
return n.application.handlerRequest(url, method)
}
func (n *nginx) allowRateLimiting(url string) bool {
if n.rateLimiter[url] == 0 {
n.rateLimiter[url] = 1
}
if n.rateLimiter[url] > n.maxAllowedRequest {
return false
}
n.rateLimiter[url]++
return true
}
type application struct{}
func (a *application) handlerRequest(url, method string) (int, string) {
if url == urlStatus && method == http.MethodGet {
return http.StatusOK, resultOK
}
if url == urlCreate && method == http.MethodPut {
return http.StatusCreated, resultCreated
}
return http.StatusNotFound, resultNotOK
}
func RunProxy() {
nginxServer := newNginxServer()
code, body := nginxServer.handlerRequest(urlStatus, http.MethodGet)
fmt.Printf("Url: %s\tHttpCode: %d\tBody: %s\n", urlStatus, code, body)
code, body = nginxServer.handlerRequest(urlStatus, http.MethodGet)
fmt.Printf("Url: %s\tHttpCode: %d\tBody: %s\n", urlStatus, code, body)
code, body = nginxServer.handlerRequest(urlStatus, http.MethodGet)
fmt.Printf("Url: %s\tHttpCode: %d\tBody: %s\n", urlStatus, code, body)
code, body = nginxServer.handlerRequest(urlStatus, http.MethodPost)
fmt.Printf("Url: %s\tHttpCode: %d\tBody: %s\n", urlStatus, code, body)
code, body = nginxServer.handlerRequest(urlStatus, http.MethodGet)
fmt.Printf("Url: %s\tHttpCode: %d\tBody: %s\n", urlStatus, code, body)
}