Skip to content

Instantly share code, notes, and snippets.

@caike
Last active July 22, 2016 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caike/a06982eeeb4293de813e6e9946bade24 to your computer and use it in GitHub Desktop.
Save caike/a06982eeeb4293de813e6e9946bade24 to your computer and use it in GitHub Desktop.
Example of concurrency in Go with web requests to Express
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()
}
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}
}
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)
}
"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