queues-go/app/routers/put.go
Egor Matveev 932f263373
All checks were successful
Deploy Dev / Build (pull_request) Successful in 38s
Deploy Dev / Push (pull_request) Successful in 25s
Deploy Dev / Deploy dev (pull_request) Successful in 8s
fix
2024-12-31 02:54:57 +03:00

53 lines
1.1 KiB
Go

package routers
import (
"encoding/json"
"net/http"
tasks "queues-go/app/storage/mongo/collections"
"time"
"go.mongodb.org/mongo-driver/bson"
)
type PutRequestBody struct {
Payload bson.M `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)
}