This commit is contained in:
Egor Matveev
2024-12-31 00:53:40 +03:00
commit c2659fb49c
16 changed files with 480 additions and 0 deletions

29
app/routers/finish.go Normal file
View File

@@ -0,0 +1,29 @@
package routers
import (
"encoding/json"
"net/http"
tasks "queues-go/app/storage/mongo/collections"
)
type FinishRequestBody struct {
Id string `json:"id"`
}
func Finish(w http.ResponseWriter, r *http.Request) {
d := json.NewDecoder(r.Body)
body := FinishRequestBody{}
err := d.Decode(&body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
err = tasks.Finish(body.Id)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
}

46
app/routers/put.go Normal file
View File

@@ -0,0 +1,46 @@
package routers
import (
"encoding/json"
"net/http"
tasks "queues-go/app/storage/mongo/collections"
"time"
)
type PutRequestBody struct {
Payload json.RawMessage `json:"payload"`
SecondsToExecute int `json:"seconds_to_execute"`
Delay *int `json:"delay"`
}
func Put(w http.ResponseWriter, r *http.Request) {
d := json.NewDecoder(r.Body)
body := PutRequestBody{}
err := d.Decode(&body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
queue := r.Header.Get("queue")
var availableFrom time.Time
if body.Delay == nil {
availableFrom = time.Now()
} else {
availableFrom = time.Now().Add(time.Second + time.Duration(*body.Delay))
}
task := tasks.InsertedTask{
Queue: queue,
Payload: body.Payload,
PutAt: time.Now(),
AvailableFrom: availableFrom,
SecondsToExecute: body.SecondsToExecute,
TakenAt: nil,
Attempts: 0,
}
err = tasks.Add(task)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
}

42
app/routers/take.go Normal file
View File

@@ -0,0 +1,42 @@
package routers
import (
"encoding/json"
"net/http"
tasks "queues-go/app/storage/mongo/collections"
)
type TaskResponse struct {
Id string `json:"id"`
Attempt int `json:"attempt"`
Payload interface{} `json:"payload"`
}
type TakeResponse struct {
Task *TaskResponse `json:"task"`
}
func Take(w http.ResponseWriter, r *http.Request) {
queue := r.Header.Get("queue")
task, err := tasks.Take(queue)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
var response TakeResponse
if task == nil {
response.Task = nil
} else {
response.Task = &TaskResponse{
Id: task.Id.Hex(),
Attempt: task.Attempts,
Payload: task.Payload,
}
}
data, err := json.Marshal(response)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(data)
}