Last active
July 22, 2016 15:32
-
-
Save caike/a06982eeeb4293de813e6e9946bade24 to your computer and use it in GitHub Desktop.
Example of concurrency in Go with web requests to Express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"demo/lib" | |
"sync" | |
) | |
func main() { | |
connections := lib.GetAllConnections() | |
var wg sync.WaitGroup | |
wg.Add(len(connections)) | |
for _, c := range connections { | |
go c.Notify(&wg) | |
} | |
wg.Wait() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package lib | |
import ( | |
"demo/httpService" | |
"sync" | |
"time" | |
) | |
type guestConnection struct { | |
ip string | |
userName string | |
isAdmin bool | |
} | |
type visitorConnection struct { | |
ip string | |
connHour int | |
} | |
type notifier interface { | |
Notify(*sync.WaitGroup) | |
} | |
func (g guestConnection) Notify(wg *sync.WaitGroup) { | |
httpService.SendNotification() | |
wg.Done() | |
} | |
func (v visitorConnection) Notify(wg *sync.WaitGroup) { | |
httpService.SendNotification() | |
wg.Done() | |
} | |
func GetAllConnections() []notifier { | |
gConn := &guestConnection{ip: "192.168.0.10", userName: "Darth Vader"} | |
vConn := &visitorConnection{ip: "192.168.0.11", connHour: time.Now().Hour()} | |
return []notifier{gConn, vConn} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package httpService | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
) | |
func SendNotification() { | |
// doing GET cause it's simpler but this should be POST | |
resp, err := http.Get("http://localhost:8080/notifications") | |
if err != nil { | |
log.Fatal("Error sending notification to remote server", err) | |
} | |
defer resp.Body.Close() | |
fmt.Println("Notification Body: ", resp.Body) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
const app = require("express")(); | |
app.get("/notifications", (req, res) => { | |
setTimeout(() => { | |
res.json("Response from ExpressJS"); | |
}, 5000); | |
}); | |
app.listen(8080, () => console.log("Listening...")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment