-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver.go
223 lines (184 loc) · 5.57 KB
/
webserver.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package main
import (
"bytes"
"code.google.com/p/go.net/websocket"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"runtime"
"time"
//"tweetanalyzer"
"github.com/geraldstanje/tweetanalyzer/src/tweetanalyzer"
)
const debug = false
const errorCounterMax = 3
const DeployTo = Boot2Docker
const (
AWSWithDocker = iota
Boot2Docker
NoDocker
)
// Client connection consists of the websocket and the client ip
type Client struct {
errorCount int
websocket *websocket.Conn
clientIP string
}
type RealtimeAnalyzer struct {
twitterstream *tweetanalyzer.TwitterStream
instagramstream *tweetanalyzer.InstagramStream
flickrstream *tweetanalyzer.FlickrStream
config tweetanalyzer.Config
activeClients map[string]Client
strChan chan string
errChan chan error
}
func (rt *RealtimeAnalyzer) changeIPAddressInFile(filename string, newStr string) error {
if len(filename) == 0 {
return fmt.Errorf("Error: invalid len of file")
}
b, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
reg := regexp.MustCompile(`[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}:[0-9]{2,5}/sock";`)
ips := reg.FindAllString(string(b), -1)
for _, ip := range ips {
newStr += "/sock\";"
b = bytes.Replace(b, []byte(ip), []byte(newStr), -1)
}
err = ioutil.WriteFile(filename, b, 0644)
return err
}
// handler for the main page
func HomeHandler(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-type", "text/html")
webpage, err := ioutil.ReadFile("home.html")
if err != nil {
http.Error(response, fmt.Sprintf("home.html file error %v", err), 500)
}
fmt.Fprint(response, string(webpage))
}
func (rt *RealtimeAnalyzer) generateGeoData() {
for {
longitude, latitude := tweetanalyzer.GenerateRandGeoLoc()
str := tweetanalyzer.IntToString(tweetanalyzer.RandInt(0, 3)) + ", " +
tweetanalyzer.FloatToString(longitude) + ", " +
tweetanalyzer.FloatToString(latitude) + ", " +
"tweet"
rt.strChan <- str
time.Sleep(200 * time.Millisecond)
}
}
func (rt *RealtimeAnalyzer) broadcastData() {
var Message = websocket.Message
var err error
tweet_count := 0
for {
select {
case str := <-rt.strChan:
for ip, _ := range rt.activeClients {
if err = Message.Send(rt.activeClients[ip].websocket, str); err != nil {
// we could not send the message to a peer
log.Println("Could not send message to ", ip, err.Error())
// work-around: https://code.google.com/p/go/issues/detail?id=3117
var tmp = rt.activeClients[ip]
tmp.errorCount += 1
rt.activeClients[ip] = tmp
if rt.activeClients[ip].errorCount >= errorCounterMax {
log.Println("Client disconnected:", ip)
delete(rt.activeClients, ip)
}
}
}
tweet_count += 1
fmt.Println(tweet_count)
}
}
}
// reference: https://github.com/Niessy/websocket-golang-chat
// WebSocket server to handle clients
func (rt *RealtimeAnalyzer) WebSocketServer(ws *websocket.Conn) {
var err error
// cleanup on server side
defer func() {
if err = ws.Close(); err != nil {
log.Println("Websocket could not be closed", err.Error())
}
}()
client := ws.Request().RemoteAddr
log.Println("New client connected:", client)
rt.activeClients[client] = Client{0, ws, client}
// wait for errChan, so the websocket stays open otherwise it'll close
err = <-rt.errChan
}
func (rt *RealtimeAnalyzer) startHTTPServer() {
http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("images/"))))
http.Handle("/", http.HandlerFunc(HomeHandler))
http.Handle("/sock", websocket.Handler(rt.WebSocketServer))
err := http.ListenAndServe(":"+rt.config.Port, nil)
rt.errChan <- err
}
func (rt *RealtimeAnalyzer) getExternalIP() string {
resp, _ := http.Get("http://myexternalip.com/raw")
defer resp.Body.Close()
contents, _ := ioutil.ReadAll(resp.Body)
ip := string(contents)
return ip[:len(ip)-1]
}
func NewRealtimeAnalyzer() *RealtimeAnalyzer {
rt := RealtimeAnalyzer{}
rt.strChan = make(chan string, 1000) // buffered channel with 1000 entries
rt.errChan = make(chan error) // unbuffered channel
rt.activeClients = make(map[string]Client)
return &rt
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
rt := NewRealtimeAnalyzer()
// read configuration file
var err error
rt.config, err = tweetanalyzer.ReadConfig("config.xml")
if err != nil {
log.Println(err)
os.Exit(1)
}
// change IP Address depending on the env to deploy
if DeployTo == AWSWithDocker {
rt.config.IPAddress = "ebsdockerhellogo-env.elasticbeanstalk.com"
rt.config.Port = "80"
} else if DeployTo == Boot2Docker {
rt.config.IPAddress = "192.168.59.103"
rt.config.Port = "8080"
} else if DeployTo == NoDocker {
rt.config.IPAddress = rt.getExternalIP()
rt.config.Port = "8080"
}
// create TwitterStream, InstagramStream
rt.twitterstream = tweetanalyzer.NewTwitterStream(rt.strChan, rt.errChan, rt.config)
rt.instagramstream = tweetanalyzer.NewInstagramStream(rt.strChan, rt.errChan, rt.config)
//rt.instagramstream.SetRedirectIP(rt.config.IPAddress)
rt.instagramstream.Create()
rt.flickrstream = tweetanalyzer.NewFlickrStream(rt.strChan, rt.errChan, rt.config)
rt.flickrstream.Create()
// replace the IP Address and Port within the HTML file
err = rt.changeIPAddressInFile("home.html", rt.config.IPAddress+":"+rt.config.Port)
if err != nil {
log.Println(err)
os.Exit(1)
}
go rt.startHTTPServer()
go rt.broadcastData()
//go rt.generateGeoData()
go rt.instagramstream.InstagramStream()
go rt.twitterstream.TwitterStream()
go rt.flickrstream.FlickrStream()
err = <-rt.errChan
if err != nil {
log.Println(err)
os.Exit(1)
}
}