about summary refs log tree commit diff
path: root/src/rest-api/handler/handler.go
blob: c904ff4fc71c56745f08c6d330ea7b0cefbf56a3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package handler

import (
	"context"
	"fmt"
	"io"
	"log"
	"net/http"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

type Handler struct {
	ch        *amqp.Channel
	queueName string
}

func NewHandler(ch *amqp.Channel, queueName string) *Handler {
	return &Handler{
		ch:        ch,
		queueName: queueName,
	}
}

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	bytes, err := io.ReadAll(io.Reader(r.Body))
	if err != nil {
		log.Fatal(err)
	}

	body := fmt.Sprint("Hello World!", r.RemoteAddr, string(bytes))

	ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
	defer cancel()

	go h.ch.PublishWithContext(ctx, "", h.queueName, false, false, amqp.Publishing{
		ContentType: "text/plain",
		Body:        []byte(body),
	})

	fmt.Fprint(w, "Hello, World!", string(bytes))
	log.Println("Request received", r.RemoteAddr, string(bytes))
}