main.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "github.com/gorilla/websocket"
  7. "github.com/unrolled/secure"
  8. "net/http"
  9. "strings"
  10. "sync"
  11. "time"
  12. )
  13. var (
  14. // BasicPort The original port without SSL certificate
  15. BasicPort = `:12080`
  16. // SSLPort "Secure" port with SSL certificate
  17. SSLPort = `:12443`
  18. // websocket.Upgrader specifies parameters for upgrading an HTTP connection to a
  19. // WebSocket connection.
  20. upGrader = websocket.Upgrader{
  21. CheckOrigin: func(r *http.Request) bool { return true },
  22. }
  23. hlSyncMap sync.Map
  24. )
  25. // Clients provides Connect instance for a job
  26. type Clients struct {
  27. clientGroup string
  28. clientName string
  29. Data map[string]string
  30. clientWs *websocket.Conn
  31. }
  32. // NewClients initializes a new Clients instance
  33. func NewClients(clientGroup string, clientName string, clientWs *websocket.Conn) *Clients {
  34. return &Clients{
  35. clientGroup: clientGroup,
  36. clientName: clientName,
  37. clientWs: clientWs,
  38. }
  39. }
  40. var hlClients sync.Map
  41. func NewClient(group string, name string, ws *websocket.Conn) *Clients {
  42. return &Clients{
  43. clientGroup: group,
  44. clientName: name,
  45. Data: make(map[string]string),
  46. clientWs: ws,
  47. }
  48. }
  49. // ws, provides inject function for a job
  50. func ws(c *gin.Context) {
  51. group, name := c.Query("group"), c.Query("name")
  52. if group == "" || name == "" {
  53. return
  54. }
  55. ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
  56. if err != nil {
  57. fmt.Println("websocket err:", err)
  58. return
  59. }
  60. client := NewClients(group, name, ws)
  61. hlSyncMap.Store(group+"->"+name, client)
  62. for {
  63. _, message, err := ws.ReadMessage()
  64. if err != nil {
  65. break
  66. }
  67. msg := string(message)
  68. check := []uint8{104, 108, 94, 95, 94}
  69. strIndex := strings.Index(msg, string(check))
  70. if strIndex >= 1 {
  71. action := msg[:strIndex]
  72. client.Data[action] = msg[strIndex+5:]
  73. fmt.Println("get_message:", client.Data[action])
  74. hlClients.Store(getGroup+"->"+getName, client)
  75. } else {
  76. fmt.Println(msg, "message error")
  77. }
  78. }
  79. defer func(ws *websocket.Conn) {
  80. _ = ws.Close()
  81. }(ws)
  82. }
  83. func QueryFunc(client *Clients, funcName string, param string) {
  84. var WriteDate string
  85. if param == "" {
  86. WriteDate = "{\"action\":\"" + funcName + "\"}"
  87. } else {
  88. WriteDate = "{\"action\":\"" + funcName + "\",\"param\":\"" + param + "\"}"
  89. }
  90. ws := client.clientWs
  91. err := ws.WriteMessage(1, []byte(WriteDate))
  92. if err != nil {
  93. fmt.Println(err, "写入数据失败")
  94. }
  95. }
  96. func Go(c *gin.Context) {
  97. getGroup, getName, Action, getParam := c.Query("group"), c.Query("name"), c.Query("action"), c.Query("param")
  98. if getGroup == "" || getName == "" {
  99. c.String(200, "input group and name")
  100. return
  101. }
  102. clientName, ok := hlClients.Load(getGroup + "->" + getName)
  103. =======
  104. hlSyncMap.Delete(group + "->" + name)
  105. defer ws.Close()
  106. }
  107. // ResultSet provides get result function for a job
  108. // you can use it to Remote operation and get results
  109. func ResultSet(c *gin.Context) {
  110. group := c.Query("group")
  111. name := c.Query("name")
  112. action := c.Query("action")
  113. param := c.Query("param")
  114. if group == "" || name == "" {
  115. c.String(200, "input group and name")
  116. return
  117. }
  118. fmt.Println(group + "->" + name)
  119. clientName, ok := hlSyncMap.Load(group + "->" + name)
  120. fmt.Println(clientName)
  121. if ok == false {
  122. c.String(200, "注入了ws?没有找到当前组和名字")
  123. return
  124. }
  125. if action == "" {
  126. c.JSON(200, gin.H{"group": group, "name": name})
  127. return
  128. }
  129. value, ko := clientName.(*Clients)
  130. if value.Data[action] == nil {
  131. value.Data[action] = make(chan string, 1)
  132. }
  133. QueryFunc(value, action, param)
  134. data := <-value.Data[action]
  135. if ko {
  136. c.JSON(200, gin.H{"status": "200", "group": value.clientGroup, "name": value.clientName, action: data})
  137. } else {
  138. c.JSON(666, gin.H{"message": "?"})
  139. }
  140. }
  141. // ClientConnectionList provides get client connect list for a job
  142. // you can use it see all Connection
  143. func ClientConnectionList(c *gin.Context) {
  144. resList := "hliang:\r\n"
  145. hlSyncMap.Range(func(key, value interface{}) bool {
  146. resList += key.(string) + "\r\n\t"
  147. return true
  148. })
  149. c.String(200, resList)
  150. }
  151. func Index(c *gin.Context) {
  152. c.String(200, "你好,我是黑脸怪~")
  153. }
  154. func TlsHandler() gin.HandlerFunc {
  155. return func(c *gin.Context) {
  156. secureMiddleware := secure.New(secure.Options{
  157. SSLRedirect: true,
  158. SSLHost: SSLPort,
  159. })
  160. err := secureMiddleware.Process(c.Writer, c.Request)
  161. if err != nil {
  162. c.Abort()
  163. return
  164. }
  165. c.Next()
  166. }
  167. }
  168. func main() {
  169. //设置获取数据的超时时间30秒
  170. r := gin.Default()
  171. r.GET("/result", ResultSet)
  172. r.GET("/ws", ws)
  173. r.GET("/list", ClientConnectionList)
  174. r.Use(TlsHandler())
  175. _ = r.Run(LocalPort)
  176. //_ = r.RunTLS(sslPort, "zhengshu.pem", "zhengshu.key")
  177. r.Run(BasicPort)
  178. //r.RunTLS(SSLPort, "zhengshu.pem", "zhengshu.key")
  179. }