1
0

main.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. action := RequestParam.Action
  179. if action == "" {
  180. GinJsonMsg(c, http.StatusOK, "请传入action来调用客户端方法")
  181. return
  182. }
  183. clientId := RequestParam.ClientId
  184. client := GetRandomClient(group, clientId)
  185. if client == nil {
  186. GinJsonMsg(c, http.StatusBadRequest, "没有找到对应的group或clientId,请通过list接口查看现有的注入")
  187. return
  188. }
  189. c2 := make(chan string, 1)
  190. go GQueryFunc(client, action, RequestParam.Param, c2)
  191. //把管道传过去,获得值就返回了
  192. c.JSON(http.StatusOK, gin.H{"status": 200, "group": client.clientGroup, "clientId": client.clientId, "data": <-c2})
  193. }
  194. func GetRandomClient(group string, clientId string) *Clients {
  195. var client *Clients
  196. // 不传递clientId时候,从group分组随便拿一个
  197. if clientId != "" {
  198. clientName, ok := hlSyncMap.Load(group + "->" + clientId)
  199. if ok == false {
  200. return nil
  201. }
  202. client, _ = clientName.(*Clients)
  203. return client
  204. }
  205. groupClients := make([]*Clients, 0)
  206. //循环读取syncMap 获取group名字的
  207. hlSyncMap.Range(func(_, value interface{}) bool {
  208. tmpClients, ok := value.(*Clients)
  209. if !ok {
  210. return true
  211. }
  212. if tmpClients.clientGroup == group {
  213. groupClients = append(groupClients, tmpClients)
  214. }
  215. return true
  216. })
  217. if len(groupClients) == 0 {
  218. return nil
  219. }
  220. // 使用随机数发生器
  221. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  222. randomIndex := r.Intn(len(groupClients))
  223. client = groupClients[randomIndex]
  224. return client
  225. }
  226. func Execjs(c *gin.Context) {
  227. var RequestParam ApiParam
  228. if err := c.ShouldBind(&RequestParam); err != nil {
  229. GinJsonMsg(c, http.StatusBadRequest, err.Error())
  230. return
  231. }
  232. Action := "_execjs"
  233. //获取参数
  234. group := RequestParam.GroupName
  235. if group == "" {
  236. GinJsonMsg(c, http.StatusBadRequest, "需要传入group")
  237. return
  238. }
  239. JsCode := RequestParam.Code
  240. if JsCode == "" {
  241. GinJsonMsg(c, http.StatusBadRequest, "请传入代码")
  242. return
  243. }
  244. clientId := RequestParam.ClientId
  245. client := GetRandomClient(group, clientId)
  246. if client == nil {
  247. GinJsonMsg(c, http.StatusBadRequest, "没有找到对应的group或clientId,请通过list接口查看现有的注入")
  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. }