main.go 9.9 KB

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