/
iezhelev
/
cppsh_micro
Обзор
Документация
Войти
/
iezhelev
/
cppsh_micro
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
cmd/command/main.go
137 строк
4 KB
iezhelev
ws server
23 мар 2025, 22:56
23 мар 2025, 22:56
ac33f5f
Код
Авторство
О чём код?
package main import ( "context" "encoding/json" "fmt" "log" "net/http" "os" "regexp" "github.com/go-redis/redis/v8" //"github.com/redis/go-redis/v9" "cppsh_micro/pkg/command" _ "github.com/lib/pq" "github.com/streadway/amqp" ) var ctx = context.Background() func main() { // Connect to RabbitMQ rabbitMQURL := "amqp://guest:guest@rabbitmq:5672/" conn, err := amqp.Dial(rabbitMQURL) if err != nil { log.Fatalf("Failed to connect to RabbitMQ: %v", err) } defer conn.Close() ch, err := conn.Channel() if err != nil { log.Fatalf("Failed to open a channel: %v", err) } defer ch.Close() // Declare a queue in RabbitMQ queueName := "data_queue" _, err = ch.QueueDeclare( queueName, // name true, // durable false, // delete when unused false, // exclusive false, // no-wait nil, // arguments ) if err != nil { log.Fatalf("Failed to declare a queue: %v", err) } // Connect to Redis rdb := redis.NewClient(&redis.Options{ Addr: os.Getenv("REDIS_URL"), Password: "", // no password DB: 0, // default DB }) patterns := []*regexp.Regexp{ regexp.MustCompile(`^/mobile/(?P<action>[^/]+)$`), regexp.MustCompile(`^/mobile/json/v2/xapi/entity/(?P<tablename>[^/]+)/(?P<action>[^/]+)$`), regexp.MustCompile(`^/mobile/json/v2/xapi/entity/(?P<tablename>[^/]+)/sn/(?P<shortname>[^/]+)/(?P<action>[^/]+)$`), regexp.MustCompile(`^/mobile/json/m/v1/entity/(?P<tablename>[^/]+)/(?P<shortname>[^/]+)/transition/(?P<transitionname>[^/]+)$`), } handler := command.NewCommandHandler(&ctx, ch, rdb) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { switch { case r.URL.Path == "/health": // Handle the /health endpoint w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) default: // Create a map to store named group values params := make(map[string]string) // Iterate through the patterns to find a match for _, pattern := range patterns { if pattern.MatchString(r.URL.Path) { // Extract named groups match := pattern.FindStringSubmatch(r.URL.Path) if match == nil { continue } for i, name := range pattern.SubexpNames() { if i > 0 && i <= len(match) { params[name] = match[i] } } // Log or use the extracted values log.Printf("Matched path: %s", r.URL.Path) log.Printf("Table Name: %s", params["tablename"]) log.Printf("Short Name: %s", params["shortname"]) if a, exists := params["action"]; exists { log.Printf("Action: %s", a) } if t, exists := params["transitionname"]; exists { log.Printf("Transition name: %s", t) } } } if r.Method == http.MethodPost { // Read the JSON body from the request var body map[string]interface{} if err := json.NewDecoder(r.Body).Decode(&body); err != nil { http.Error(w, "Invalid JSON body", http.StatusBadRequest) return } // Convert the body to JSON bytes jsonData, err := json.Marshal(body) if err != nil { http.Error(w, "Failed to encode JSON", http.StatusInternalServerError) return } // Pass the JSON data to StoreData handler.StoreData(queueName, jsonData, params) w.WriteHeader(http.StatusOK) fmt.Fprint(w, `{"status":"data stored"}`) } else { w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, "Not Found") return } } }) //http.HandleFunc("/user", handler.CreateUser) log.Println("Command Service started on :8080") if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatalf("Failed to start HTTP server: %s", err) } }