-
Notifications
You must be signed in to change notification settings - Fork 0
/
microfrontends.go
122 lines (90 loc) · 2.14 KB
/
microfrontends.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package microfrontends
import (
"fmt"
"html/template"
"io/ioutil"
"net/http"
"github.com/hasangenc0/microfrontends/pkg/client"
"github.com/hasangenc0/microfrontends/pkg/types"
)
type Gateway = types.Gateway
type Page = types.Page
type App struct {
Gateway []Gateway
Page Page
Response http.ResponseWriter
}
func (app *App) setHeaders() {
app.Response.Header().Set("Transfer-Encoding", "chunked")
}
func (app *App) initialize() {
flusher, ok := app.Response.(http.Flusher)
if !ok {
panic("expected http.ResponseWriter to be an http.Flusher")
}
tmpl, err := template.New(app.Page.Name).Parse(app.Page.Content)
if err != nil {
panic("An Error occured when parsing html")
}
err = tmpl.Execute(app.Response, "")
if err != nil {
panic("Error in Template.Execute")
}
flusher.Flush()
}
func (app *App) sendChunk(gateway Gateway, ch chan http.Flusher) {
var flusher, ok = app.Response.(http.Flusher)
if !ok {
panic("expected http.ResponseWriter to be an http.Flusher")
}
_client := &http.Client{}
req, err := http.NewRequest(gateway.GetHTTPMethod(), gateway.GetUrl(), nil)
if err != nil {
panic(err)
}
resp, err := _client.Do(req)
if err != nil {
ch <- nil
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
bodyString := string(bodyBytes)
chunk := client.GetView(gateway.Name, bodyString)
fmt.Fprintf(app.Response, chunk)
}
ch <- flusher
}
func (app *App) finish() {
flusher, ok := app.Response.(http.Flusher)
if !ok {
panic("expected http.ResponseWriter to be an http.Flusher")
}
_, err := app.Response.Write([]byte(""))
if err != nil {
panic("expected http.ResponseWriter to be an http.Flusher")
}
flusher.Flush()
}
func (app *App) Init() {
app.setHeaders()
app.initialize()
var flusher = make(chan http.Flusher)
for _, gateway := range app.Gateway {
go app.sendChunk(gateway, flusher)
}
for range app.Gateway {
flusher, ok := <-flusher
if !ok {
panic("expected http.ResponseWriter to be an http.Flusher")
}
if flusher != nil {
flusher.Flush()
}
}
app.finish()
}