Private
Public Access
0
0

add more comments, clean up module

This commit is contained in:
teizz
2021-10-24 12:32:32 +02:00
parent 5c38e74522
commit 53013812a9
8 changed files with 121 additions and 182 deletions

29
get.go
View File

@@ -6,19 +6,22 @@ import (
"sync/atomic"
)
func handleGet(pathID string, w http.ResponseWriter, r *http.Request) {
queue := &Queue{ch: make(chan Transfer)}
if p, loaded := paths.LoadOrStore(pathID, queue); loaded {
queue = p.(*Queue)
debug("%s [GET] Loads path", pathID)
} else {
debug("%s [GET] Created path", pathID)
// handleGet simply attempts to relay whatever data is received from the first
// available POST request into this GET request on the same path.
// if there is no POST waiting, it will block indefinitely until it either finds
// a POST or the connection is cancelled.
func (pw *Pathway) handleGet(pathID string, w http.ResponseWriter, r *http.Request) {
// GET creates a new path preemptively
queue := &transferQueue{ch: make(chan httpTransfer)}
if p, loaded := pw.LoadOrStore(pathID, queue); loaded {
// GET successfully loads a path instead
queue = p.(*transferQueue)
}
atomic.AddInt32(&queue.gets, 1)
select {
// either a POST presents itself on the other side of the queue's channel
case transfer := <-queue.ch:
debug("%s [GET] Reads from path", pathID)
if transfer.contentlength != "" {
w.Header().Set("Content-Length", transfer.contentlength)
}
@@ -26,17 +29,17 @@ func handleGet(pathID string, w http.ResponseWriter, r *http.Request) {
if err != nil {
transfer.reader.Close()
}
debug("%s [GET] Sends done", pathID)
close(transfer.done)
// or the request is cancelled, and this GET can continue to finish
case <-r.Context().Done():
debug("%s [GET] Cancels path", pathID)
}
// if this was indeed the last GET and there are no more new POST requests
// waiting, then go ahead and close the queue and remove the path
if atomic.AddInt32(&queue.gets, -1) <= 0 {
if atomic.LoadInt32(&queue.posts) <= 0 {
paths.Delete(pathID)
debug("%s [GET] Removes path", pathID)
pw.Delete(pathID)
close(queue.ch)
}
}
info("%s [GET] Finishes", pathID)
}