From 3e876c6d03c766193c62c2c0148efdaf43b69d3e Mon Sep 17 00:00:00 2001 From: Baitinq Date: Thu, 2 May 2024 15:43:24 +0200 Subject: Change module name and cleanup http handler --- src/rest-api/handler/BUILD.bazel | 9 ++++++++ src/rest-api/handler/handler.go | 44 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 src/rest-api/handler/BUILD.bazel create mode 100644 src/rest-api/handler/handler.go (limited to 'src/rest-api/handler') diff --git a/src/rest-api/handler/BUILD.bazel b/src/rest-api/handler/BUILD.bazel new file mode 100644 index 0000000..a5638f4 --- /dev/null +++ b/src/rest-api/handler/BUILD.bazel @@ -0,0 +1,9 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "handler", + srcs = ["handler.go"], + importpath = "github.com/Baitinq/fs-tracer-backend/src/rest-api/handler", + visibility = ["//visibility:public"], + deps = ["@com_github_rabbitmq_amqp091_go//:amqp091-go"], +) diff --git a/src/rest-api/handler/handler.go b/src/rest-api/handler/handler.go new file mode 100644 index 0000000..b5c3ae2 --- /dev/null +++ b/src/rest-api/handler/handler.go @@ -0,0 +1,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 { + panic(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)) +} -- cgit 1.4.1