I am working on an http endpoint that will receive a request from a client and block until it receives an "ack" for that request from another server or until it passes a timeout. The communication between my code and the server is not included in this sample, but you can assume that for each request, an ack may be received eventually.
Since many requests will pass through my module in short periods of time, I cannot assume that a given ack is related the the request I am blocking on. EDIT: Clarification here since it has caused some confusion. Both requests and acks are received by the controller from external sources. This is why I am handling them asychronously. /EDIT For this reason, my code places acks back on the channel if they are not relevant. It is also important to note that http.ListenAndServe calls my functions asynchronously.
If the request is acked within the timeout, there are no problems. However, it the ack comes after the timeout has passed, it will be added to a channel and never removed. This will cause the channel to fill up. I am afraid to use a "cancel" channel because it is also possible that no ack will be received for a given request, causing the cancel channel to fill as well.
The Question: How can I keep late acks from filling my channel?/How can I identify and remove late acks?
Code below. No play.golang.org link because http.ListenAndServe :/
package main
import (
"fmt"
"net/http"
"time"
)
const timeout = 10
func startEndpoint(w http.ResponseWriter, r *http.Request) {
var ack string
timer := time.NewTimer(time.Second * timeout)
defer timer.Stop()
m := r.RequestURI[len("/start/"):]
fmt.Print(m)
AckRecycle:
for {
select {
case ack = <-acks:
if ack == m {
//What we found was our own ack
fmt.Print("+")
w.Write([]byte("Ack received for " + ack))
break AckRecycle
} else {
//What we found on the channel wasn't for us
fmt.Print(".")
time.Sleep(time.Millisecond * 100)
acks <- ack
}
case <-timer.C:
//We ran out of time waiting for our ack
w.Write([]byte("Timeout waiting for " + m))
break AckRecycle
default:
//Channel was empty
fmt.Print("-")
time.Sleep(time.Millisecond * 100)
}
}
return
}
func ackEndpoint(w http.ResponseWriter, r *http.Request) {
ack := r.RequestURI[len("/ack/"):]
acks <- ack
fmt.Print("Ack for " + ack)
w.Write([]byte("Thanks!"))
return
}
var acks = make(chan string, 10)
func main() {
http.HandleFunc("/ack/", ackEndpoint)
http.HandleFunc("/start/", startEndpoint)
http.ListenAndServe("127.0.0.1:8888", nil)
}
NOTE: To test this, run it on your local machine. Curl/Wget 127.0.0.1:8888/start/bob
and then Curl/Wget 127.0.0.1:8888/ack/bob
. You can replace bob with any string to see the behavior.
I'm new to Go. Feel free to provide other feedback in the comments.