/
gateway.go
80 lines (69 loc) · 2.08 KB
/
gateway.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
package server
import (
"context"
"errors"
"log"
"net/http"
"github.com/amdf/conv-get-img/internal/config"
pb "github.com/amdf/conv-get-img/svc"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
var allowedOrigins = []string{
"http://localhost:8080",
"http://127.0.0.1:8080",
"http://localhost:8081",
"http://127.0.0.1:8081",
}
func cors(h http.Handler, allowedOrigins []string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
providedOrigin := r.Header.Get("Origin")
matches := false
for _, allowedOrigin := range allowedOrigins {
if providedOrigin == allowedOrigin {
matches = true
break
}
}
if matches {
w.Header().Set("Access-Control-Allow-Origin", providedOrigin)
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization, ResponseType, grpc-metadata-log-level")
}
if r.Method == "OPTIONS" {
return
}
h.ServeHTTP(w, r)
})
}
func (srv ConvGetImageServer) RunGateway() {
//TODO: handle errors another way
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Note: Make sure the gRPC server is running properly and accessible
mux := runtime.NewServeMux()
conn, err := grpc.DialContext(
ctx,
config.GetServerAddress(),
//grpc.WithInsecure(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
log.Fatalln("fail to dial rpc", err)
}
err = pb.RegisterConvGetImageHandler(ctx, mux, conn)
if err != nil {
log.Fatalln("fail to register http", err)
}
log.Println("starting http server at ", config.GetGatewayAddress())
gatewayServer := &http.Server{
Addr: config.GetGatewayAddress(),
Handler: cors(mux, allowedOrigins),
}
// Start HTTP server (and proxy calls to gRPC server endpoint)
if err = gatewayServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalln("fail to serve http", err)
}
}