main.go 10 KB

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