Skip to content

Instantly share code, notes, and snippets.

@abonec
Last active February 14, 2019 13:24
Show Gist options
  • Save abonec/49d201571d406db95fbb57e23ce8e9c5 to your computer and use it in GitHub Desktop.
Save abonec/49d201571d406db95fbb57e23ce8e9c5 to your computer and use it in GitHub Desktop.
shared request
package main
import (
"net/http"
"sync"
)
type Response struct {
}
type Request struct {
from string
to string
waitChan chan struct{}
response Response
}
func NewRequest(from, to string) *Request {
r := Request{from: from, to: to, waitChan: make(chan struct{})}
go r.Call()
return &r
}
func (r *Request) Call() {
_, _ = http.Get("http://service.com")
r.response = Response{}
close(r.waitChan)
}
func (r *Request) WaitResponse() Response {
<-r.waitChan
return r.response
}
type Key struct {
From string
To string
}
type Requester struct {
mu sync.RWMutex
requests map[Key]*Request
}
func (r *Requester) Request(from, to string) Response {
key := Key{From: from, To: to}
r.mu.RLock()
req, ok := r.requests[key]
r.mu.RUnlock()
if !ok {
req := NewRequest(from, to)
r.mu.Lock()
r.requests[key] = req
r.mu.Unlock()
}
response := req.WaitResponse()
r.mu.Lock()
delete(r.requests, key)
r.mu.Unlock()
return response
}
func NewRequester() *Requester {
return &Requester{
requests: make(map[Key]*Request),
}
}
func main() {
r := NewRequester()
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
response := r.Request("A", "B")
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment