-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
89 lines (67 loc) · 1.76 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
89
package main
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/time/rate"
)
const API_KEY = "YOUR_API_KEY"
func main() {
apiGatewayURL := "http://localhost:8080"
microserviceOneURL := "http://localhost:8081"
microserviceTwoURL := "http://localhost:8082"
proxyOne := createReverseProxy(microserviceOneURL)
proxyTwo := createReverseProxy(microserviceTwoURL)
r := gin.Default()
r.Use(authenticate())
r.Use(rateLimit())
r.Any("/service_one/*path", proxyOne)
r.Any("/service_two/*path", proxyTwo)
// run how other microservices
go runMicroserviceOne()
go runMicroserviceTwo()
log.Printf("Starting server API Gateway on %s", apiGatewayURL)
log.Fatal(r.Run(":8080"))
}
func createReverseProxy(targetURL string) func(*gin.Context) {
target, err := url.Parse(targetURL)
if err != nil {
log.Fatalf("Error parsing url: %v", err)
}
proxy := httputil.NewSingleHostReverseProxy(target)
return func(c *gin.Context) {
log.Printf("Proxying request: %s", c.Request.URL)
c.Request.URL.Path = strings.TrimPrefix(c.Request.URL.Path, "/service_one")
c.Request.URL.Path = strings.TrimPrefix(c.Request.URL.Path, "/service_two")
proxy.ServeHTTP(c.Writer, c.Request)
}
}
func authenticate() gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Header.Get("X-API-KEY") != API_KEY {
c.AbortWithStatusJSON(
http.StatusUnauthorized,
gin.H{"error": "unauthorized"},
)
return
}
c.Next()
}
}
func rateLimit() gin.HandlerFunc {
limiter := rate.NewLimiter(rate.Every(1*time.Second), 5)
return func(c *gin.Context) {
if !limiter.Allow() {
c.AbortWithStatusJSON(
http.StatusTooManyRequests,
gin.H{"error": "too many requests"},
)
return
}
c.Next()
}
}