Create a gist now

Instantly share code, notes, and snippets.

@caike /a-main.go
Last active Jul 22, 2016

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