queues-go/app/routers/put.go
Egor Matveev 0d2abaf34e
Some checks failed
Deploy Dev / Build (pull_request) Failing after 19s
Deploy Dev / Push (pull_request) Has been skipped
Deploy Dev / Deploy dev (pull_request) Has been skipped
fix
2024-12-31 00:57:54 +03:00

51 lines
1.1 KiB
Go

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)
}