|
- package controller
-
- import (
- "context"
- "encoding/json"
- "fmt"
- "net/http"
-
- "github.com/AFASystems/presence/internal/pkg/model"
- "github.com/AFASystems/presence/internal/pkg/service"
- "github.com/gorilla/mux"
- "github.com/segmentio/kafka-go"
- "gorm.io/gorm"
- )
-
- func ParserAddController(db *gorm.DB, writer *kafka.Writer, ctx context.Context) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- decoder := json.NewDecoder(r.Body)
- var config model.Config
-
- if err := decoder.Decode(&config); err != nil {
- http.Error(w, err.Error(), 400)
- return
- }
-
- db.Create(&config)
-
- kp := model.KafkaParser{
- ID: "add",
- Config: config,
- }
-
- if err := service.SendParserConfig(kp, writer, ctx); err != nil {
- http.Error(w, "Unable to send parser config to kafka broker", 400)
- fmt.Printf("Unable to send parser config to kafka broker %v\n", err)
- return
- }
-
- w.Write([]byte("ok"))
- }
- }
-
- func ParserListController(db *gorm.DB) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- var configs []model.Config
- db.Find(&configs)
- res, err := json.Marshal(configs)
- if err != nil {
- http.Error(w, err.Error(), 400)
- return
- }
-
- w.Write(res)
- }
- }
-
- func ParserDeleteController(db *gorm.DB, writer *kafka.Writer, ctx context.Context) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- id := mux.Vars(r)["id"]
- if res := db.Delete(&model.Config{}, "name = ?", id); res.RowsAffected == 0 {
- http.Error(w, "no parser config with such name found", 400)
- return
- }
-
- kp := model.KafkaParser{
- ID: "delete",
- Name: id,
- }
-
- if err := service.SendParserConfig(kp, writer, ctx); err != nil {
- http.Error(w, "Unable to send parser config to kafka broker", 400)
- fmt.Printf("Unable to send parser config to kafka broker %v\n", err)
- return
- }
-
- w.Write([]byte("ok"))
- }
- }
-
- func ParserUpdateController(db *gorm.DB, writer *kafka.Writer, ctx context.Context) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- id := mux.Vars(r)["id"]
-
- if err := db.First(&model.Config{}, "name = ?", id).Error; err != nil {
- http.Error(w, err.Error(), 400)
- return
- }
-
- decoder := json.NewDecoder(r.Body)
- var config model.Config
-
- if err := decoder.Decode(&config); err != nil {
- http.Error(w, err.Error(), 400)
- return
- }
-
- kp := model.KafkaParser{
- ID: "update",
- Name: config.Name,
- Config: config,
- }
-
- db.Save(&config)
- if err := service.SendParserConfig(kp, writer, ctx); err != nil {
- http.Error(w, "Unable to send parser config to kafka broker", 400)
- fmt.Printf("Unable to send parser config to kafka broker %v\n", err)
- return
- }
-
- w.Write([]byte("ok"))
- }
- }
|