main.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. package main
  2. import (
  3. "JsRpc/config"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/gin-gonic/gin"
  7. "github.com/gorilla/websocket"
  8. log "github.com/sirupsen/logrus"
  9. "github.com/unrolled/secure"
  10. "math/rand"
  11. "net/http"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. )
  17. var (
  18. upGrader = websocket.Upgrader{
  19. CheckOrigin: func(r *http.Request) bool { return true },
  20. }
  21. hlSyncMap sync.Map
  22. gm = &sync.Mutex{}
  23. defaultTimeout = 30
  24. isPrint = true
  25. )
  26. // Clients 客户端信息
  27. type Clients struct {
  28. clientGroup string
  29. clientId string
  30. actionData map[string]chan string
  31. clientWs *websocket.Conn
  32. }
  33. // Message 请求和传递请求
  34. type Message struct {
  35. Action string `json:"action"`
  36. Param string `json:"param"`
  37. }
  38. type ApiParam struct {
  39. GroupName string `form:"group" json:"group"`
  40. ClientId string `form:"clientId" json:"clientId"`
  41. Action string `form:"action" json:"action"`
  42. Param string `form:"param" json:"param"`
  43. }
  44. type logWriter struct{}
  45. func (w logWriter) Write(p []byte) (n int, err error) {
  46. return len(p), nil
  47. }
  48. // is print?
  49. func logPrint(p ...interface{}) {
  50. if isPrint {
  51. log.Infoln(p)
  52. }
  53. }
  54. // NewClient initializes a new Clients instance
  55. func NewClient(group string, uid string, ws *websocket.Conn) *Clients {
  56. return &Clients{
  57. clientGroup: group,
  58. clientId: uid,
  59. actionData: make(map[string]chan string, 1), // action有消息后就保存到chan里
  60. clientWs: ws,
  61. }
  62. }
  63. func GinJsonMsg(c *gin.Context, code int, msg string) {
  64. c.JSON(code, gin.H{"status": code, "data": msg})
  65. return
  66. }
  67. // ws, provides inject function for a job
  68. func ws(c *gin.Context) {
  69. group, clientId := c.Query("group"), c.Query("clientId")
  70. //必须要group名字,不然不让它连接ws
  71. if group == "" {
  72. return
  73. }
  74. //没有给客户端id的话 就用时间戳给他生成一个
  75. if clientId == "" {
  76. millisId := time.Now().UnixNano() / int64(time.Millisecond)
  77. clientId = fmt.Sprintf("%d", millisId)
  78. }
  79. wsClient, err := upGrader.Upgrade(c.Writer, c.Request, nil)
  80. if err != nil {
  81. log.Error("websocket err:", err)
  82. return
  83. }
  84. client := NewClient(group, clientId, wsClient)
  85. hlSyncMap.Store(group+"->"+clientId, client)
  86. logPrint("新上线group:" + group + ",clientId:->" + clientId)
  87. for {
  88. //等待数据
  89. _, message, err := wsClient.ReadMessage()
  90. if err != nil {
  91. break
  92. }
  93. msg := string(message)
  94. check := []uint8{104, 108, 94, 95, 94}
  95. strIndex := strings.Index(msg, string(check))
  96. if strIndex >= 1 {
  97. action := msg[:strIndex]
  98. client.actionData[action] <- msg[strIndex+5:]
  99. logPrint("get_message:", msg[strIndex+5:])
  100. } else {
  101. log.Error(msg, "message error")
  102. }
  103. }
  104. defer func(ws *websocket.Conn) {
  105. _ = ws.Close()
  106. logPrint(group+"->"+clientId, "下线了")
  107. hlSyncMap.Range(func(key, value interface{}) bool {
  108. //client, _ := value.(*Clients)
  109. if key == group+"->"+clientId {
  110. hlSyncMap.Delete(key)
  111. }
  112. return true
  113. })
  114. }(wsClient)
  115. }
  116. func wsTest(c *gin.Context) {
  117. testClient, _ := upGrader.Upgrade(c.Writer, c.Request, nil)
  118. for {
  119. //等待数据
  120. _, message, err := testClient.ReadMessage()
  121. if err != nil {
  122. break
  123. }
  124. msg := string(message)
  125. logPrint("接收到测试消息", msg)
  126. _ = testClient.WriteMessage(websocket.BinaryMessage, []byte(msg))
  127. }
  128. defer func(ws *websocket.Conn) {
  129. _ = ws.Close()
  130. }(testClient)
  131. }
  132. // GQueryFunc 发送请求到客户端
  133. func GQueryFunc(client *Clients, funcName string, param string, resChan chan<- string) {
  134. WriteDate := Message{}
  135. WriteDate.Action = funcName
  136. if param == "" {
  137. WriteDate.Param = ""
  138. } else {
  139. WriteDate.Param = param
  140. }
  141. data, _ := json.Marshal(WriteDate)
  142. clientWs := client.clientWs
  143. if client.actionData[funcName] == nil {
  144. client.actionData[funcName] = make(chan string, 1) //此次action初始化1个消息
  145. }
  146. gm.Lock()
  147. err := clientWs.WriteMessage(1, data)
  148. gm.Unlock()
  149. if err != nil {
  150. fmt.Println(err, "写入数据失败")
  151. }
  152. resultFlag := false
  153. for i := 0; i < defaultTimeout*10; i++ {
  154. if len(client.actionData[funcName]) > 0 {
  155. res := <-client.actionData[funcName]
  156. resChan <- res
  157. resultFlag = true
  158. break
  159. }
  160. time.Sleep(time.Millisecond * 100)
  161. }
  162. // 循环完了还是没有数据,那就超时退出
  163. if true != resultFlag {
  164. resChan <- "黑脸怪:timeout"
  165. }
  166. defer func() {
  167. close(resChan)
  168. }()
  169. }
  170. // GetResult 接收web请求参数,并发给客户端获取结果
  171. func GetResult(c *gin.Context) {
  172. var RequestParam ApiParam
  173. if err := c.ShouldBind(&RequestParam); err != nil {
  174. GinJsonMsg(c, http.StatusBadRequest, err.Error())
  175. return
  176. }
  177. group := RequestParam.GroupName
  178. if group == "" {
  179. GinJsonMsg(c, http.StatusBadRequest, "需要传入group")
  180. }
  181. groupClients := make(map[string]*Clients)
  182. //循环读取syncMap 获取group名字的
  183. hlSyncMap.Range(func(key, value interface{}) bool {
  184. k := key.(string)
  185. if strings.HasPrefix(k, group+"->") {
  186. client := value.(*Clients)
  187. groupClients[k] = client
  188. }
  189. return true
  190. })
  191. if len(groupClients) == 0 {
  192. GinJsonMsg(c, http.StatusBadRequest, "没有找到注入的group:"+group)
  193. return
  194. }
  195. action := RequestParam.Action
  196. if action == "" {
  197. GinJsonMsg(c, http.StatusOK, "请传入action来调用客户端方法")
  198. return
  199. }
  200. clientId := RequestParam.ClientId
  201. var client *Clients
  202. // 不传递clientId时候,从group分组随便拿一个
  203. if clientId == "" {
  204. groupKeys := make([]string, 0, len(groupClients))
  205. for k := range groupClients {
  206. groupKeys = append(groupKeys, k)
  207. }
  208. // 使用随机数发生器
  209. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  210. randomIndex := r.Intn(len(groupKeys)) // 随机拿一个group开头的
  211. clientName := groupKeys[randomIndex] // group->clientId
  212. client = groupClients[clientName]
  213. } else {
  214. clientName, ok := hlSyncMap.Load(group + "->" + clientId)
  215. if ok == false {
  216. GinJsonMsg(c, http.StatusBadRequest, "没有找到group,clientId:"+group+"->"+clientId)
  217. return
  218. }
  219. //取一个ws客户端
  220. client, _ = clientName.(*Clients)
  221. }
  222. c2 := make(chan string, 1)
  223. go GQueryFunc(client, action, RequestParam.Param, c2)
  224. //把管道传过去,获得值就返回了
  225. c.JSON(http.StatusOK, gin.H{"status": 200, "group": client.clientGroup, "clientId": client.clientId, "data": <-c2})
  226. }
  227. func Execjs(c *gin.Context) {
  228. var getGroup, getName, JsCode string
  229. Action := "_execjs"
  230. //获取参数
  231. getGroup, getName, JsCode = c.Query("group"), c.Query("name"), c.Query("jscode")
  232. //如果获取不到 说明是post提交的
  233. if getGroup == "" && getName == "" {
  234. //切换post获取方式
  235. getGroup, getName, JsCode = c.PostForm("group"), c.PostForm("name"), c.PostForm("jscode")
  236. }
  237. if getGroup == "" || getName == "" {
  238. c.JSON(400, gin.H{"status": 400, "data": "input group and name"})
  239. return
  240. }
  241. logPrint(getGroup, getName, JsCode)
  242. clientName, ok := hlSyncMap.Load(getGroup + "->" + getName)
  243. if ok == false {
  244. c.JSON(400, gin.H{"status": 400, "data": "注入了ws?没有找到当前组和名字"})
  245. return
  246. }
  247. //取一个ws客户端
  248. client, ko := clientName.(*Clients)
  249. if !ko {
  250. return
  251. }
  252. c2 := make(chan string)
  253. go GQueryFunc(client, Action, JsCode, c2)
  254. c.JSON(200, gin.H{"status": "200", "group": client.clientGroup, "name": client.clientId, "data": <-c2})
  255. }
  256. func GetList(c *gin.Context) {
  257. var groupMap []string
  258. hlSyncMap.Range(func(key, _ interface{}) bool {
  259. k := key.(string)
  260. groupMap = append(groupMap, k)
  261. return true
  262. })
  263. c.JSON(http.StatusOK, gin.H{"status": 200, "data": groupMap})
  264. }
  265. func Index(c *gin.Context) {
  266. c.String(200, "你好,我是黑脸怪~")
  267. }
  268. func TlsHandler(HttpsHost string) gin.HandlerFunc {
  269. return func(c *gin.Context) {
  270. secureMiddleware := secure.New(secure.Options{
  271. SSLRedirect: true,
  272. SSLHost: HttpsHost,
  273. })
  274. err := secureMiddleware.Process(c.Writer, c.Request)
  275. if err != nil {
  276. c.Abort()
  277. return
  278. }
  279. c.Next()
  280. }
  281. }
  282. func main() {
  283. JsRpc := " __ _______..______ .______ ______ \n | | / || _ \\ | _ \\ / |\n | | | (----`| |_) | | |_) | | ,----'\n.--. | | \\ \\ | / | ___/ | | \n| `--' | .----) | | |\\ \\----.| | | `----.\n \\______/ |_______/ | _| `._____|| _| \\______|\n \n"
  284. fmt.Print(JsRpc)
  285. log.SetFormatter(&log.TextFormatter{
  286. ForceColors: true, // 强制终端输出带颜色日志
  287. FullTimestamp: true, // 显示完整时间戳
  288. TimestampFormat: "2006-01-02 15:04:05",
  289. })
  290. ConfigPath := "./config.yaml"
  291. MainConf := config.ConfStruct{
  292. BasicListen: `:12080`,
  293. HttpsServices: config.HttpsConfig{
  294. IsEnable: false,
  295. HttpsListen: `:12443`,
  296. },
  297. DefaultTimeOut: defaultTimeout,
  298. }
  299. _ = config.InitConf(ConfigPath, &MainConf)
  300. if MainConf.CloseWebLog {
  301. // 将默认的日志输出器设置为空
  302. gin.DefaultWriter = logWriter{}
  303. }
  304. if MainConf.CloseLog {
  305. isPrint = false
  306. }
  307. defaultTimeout = MainConf.DefaultTimeOut
  308. gin.SetMode(gin.ReleaseMode)
  309. r := gin.Default()
  310. r.GET("/", Index)
  311. r.GET("/go", GetResult)
  312. r.POST("/go", GetResult)
  313. r.GET("/ws", ws)
  314. r.GET("/wst", wsTest)
  315. r.GET("/execjs", Execjs)
  316. r.POST("/execjs", Execjs)
  317. r.GET("/list", GetList)
  318. if MainConf.HttpsServices.IsEnable {
  319. r.Use(TlsHandler(MainConf.HttpsServices.HttpsListen))
  320. go func() {
  321. err := r.RunTLS(
  322. MainConf.HttpsServices.HttpsListen,
  323. MainConf.HttpsServices.PemPath,
  324. MainConf.HttpsServices.KeyPath,
  325. )
  326. if err != nil {
  327. log.Error(err)
  328. }
  329. }()
  330. }
  331. var sb strings.Builder
  332. sb.WriteString("当前监听地址:")
  333. sb.WriteString(MainConf.BasicListen)
  334. sb.WriteString(" tls启用状态:")
  335. sb.WriteString(strconv.FormatBool(MainConf.HttpsServices.IsEnable))
  336. if MainConf.HttpsServices.IsEnable {
  337. sb.WriteString(" https监听地址:")
  338. sb.WriteString(MainConf.HttpsServices.HttpsListen)
  339. }
  340. log.Infoln(sb.String())
  341. err := r.Run(MainConf.BasicListen)
  342. if err != nil {
  343. log.Error(err)
  344. }
  345. }