api.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "math/big"
  7. "os"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "git.ali33.ru/fcg-xvii/go-tools/json"
  12. )
  13. var (
  14. idContext int32 = 0
  15. contextStore = new(sync.Map)
  16. )
  17. func getContextID() int {
  18. return int(atomic.AddInt32(&idContext, 1))
  19. }
  20. func messageIncoming(mes *Message) {
  21. mData := mes.Data()
  22. if mData.String("type", "") == "event" {
  23. // event
  24. } else {
  25. command := mData.String("command", "")
  26. switch command {
  27. case "method":
  28. log.Println("METHOD")
  29. randomNum, check := checkBigInt(mes, "random_num")
  30. if !check {
  31. randomNum = big.NewInt(1000000)
  32. }
  33. message := mData.String(
  34. "message",
  35. "Демонстрация работы алгоритмов шифрования Диффи-Хеллмана и Эль-Гамаля на эллиптических кривых и атаки на них.",
  36. )
  37. deadline := time.Now().Add(time.Duration(mData.Int("deadline_sec", 600)) * time.Second)
  38. contextID := getContextID()
  39. mes.SendResponse(json.Map{
  40. "context_id": contextID,
  41. "random_num": randomNum,
  42. "deadline": deadline.Unix(),
  43. "message": message,
  44. })
  45. ctx, cancel := context.WithDeadline(mes.Client().Context(), deadline)
  46. contextStore.Store(contextID, cancel)
  47. go func() {
  48. cl := mes.Client()
  49. for e := range MethodCurve(randomNum, message, ctx, contextID) {
  50. cl.SendSingle(e.Map())
  51. }
  52. log.Println("CONTEXT_STOPPED", contextID)
  53. }()
  54. case "context_stop":
  55. contextID := mData.Int32("context_id", -1)
  56. if contextID == -1 {
  57. mes.SendResponse(json.Map{
  58. "error": true,
  59. "text": "Ожидается context_id",
  60. })
  61. return
  62. }
  63. cancel, check := contextStore.LoadAndDelete(contextID)
  64. if !check {
  65. mes.SendResponse(json.Map{
  66. "error": true,
  67. "text": fmt.Sprintf("контекст [ %s ] не найден", contextID),
  68. })
  69. return
  70. }
  71. cancel.(context.CancelFunc)()
  72. mes.SendResponse(json.Map{
  73. "context_id": contextID,
  74. "text": "Контекст остановлен",
  75. })
  76. case "exit":
  77. os.Exit(0)
  78. default:
  79. if mes.IsResponsable() {
  80. mes.SendResponse(json.Map{
  81. "error": true,
  82. "text": fmt.Sprintf("команда [ %s ] не найдена", command),
  83. })
  84. }
  85. }
  86. }
  87. mData.LogPretty()
  88. }