Skip to content

Instantly share code, notes, and snippets.

@adityathebe
Created September 5, 2020 15:36
Show Gist options
  • Save adityathebe/253dd9c044114fb9722f9889c8cad774 to your computer and use it in GitHub Desktop.
Save adityathebe/253dd9c044114fb9722f9889c8cad774 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
name := query.Get("name")
fmt.Println("Query", name)
// Pass it to the worker
jobQueue <- name
// Send response
fmt.Fprintf(w, "Hello %s", name)
}
package main
import "net/http"
var jobQueue chan string
func main() {
jobQueue = make(chan string)
worker := Worker{maxWorkers: 2}
worker.start()
http.HandleFunc("/", handler)
http.ListenAndServe(":8000", nil)
}
package main
import (
"fmt"
"time"
)
func doWork(val string) string {
fmt.Println("Worker", val)
time.Sleep(10 * time.Second)
return val
}
// Worker listens to the jobQueue Channel
type Worker struct {
maxWorkers int
}
func (w Worker) start() {
for i := 0; i < w.maxWorkers; i++ {
go func() {
fmt.Println("Coroutine Running ...")
for x := range jobQueue {
x := doWork(x)
fmt.Println("Result", x)
}
}()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment