Forráskód Böngészése

Add files via upload

hliang 3 éve
szülő
commit
49ce51ab84
4 módosított fájl, 334 hozzáadás és 0 törlés
  1. 79 0
      JsEnv.js
  2. 9 0
      go.mod
  3. 60 0
      go.sum
  4. 186 0
      main.go

+ 79 - 0
JsEnv.js

@@ -0,0 +1,79 @@
+function Hlclient(wsURL) {
+    this.wsURL = wsURL;
+    this.handlers = {};
+    this.socket = {};
+
+    if (!wsURL) {
+        throw new Error('wsURL can not be empty!!')
+    }
+    this.connect()
+}
+
+Hlclient.prototype.connect = function () {
+    console.log('begin of connect to wsURL: ' + this.wsURL);
+    var _this = this;
+    try {
+        this.socket["ySocket"] = new WebSocket(this.wsURL);
+        this.socket["ySocket"].onmessage = function (e) {
+            console.log("send func", e.data);
+            _this.handlerRequest(e.data);
+        }
+    } catch (e) {
+        console.log("connection failed,reconnect after 30s");
+        setTimeout(function () {
+            _this.connect()
+        }, 30000)
+    }
+    this.socket["ySocket"].onclose = function () {
+        console.log("connection failed,reconnect after 30s");
+        setTimeout(function () {
+            _this.connect()
+        }, 30000)
+    }
+
+};
+Hlclient.prototype.send = function (msg) {
+    this.socket["ySocket"].send(msg)
+}
+
+Hlclient.prototype.regAction = function (func_name, func) {
+    if (typeof func_name !== 'string') {
+        throw new Error("an func_name must be string");
+    }
+    if (typeof func !== 'function') {
+        throw new Error("must be function");
+    }
+    console.log("register func_name: " + func_name);
+    this.handlers[func_name] = func;
+
+}
+Hlclient.prototype.handlerRequest = function (requestJson) {
+	var _this = this;
+	var result=JSON.parse(requestJson);
+	console.log(result)
+	if (!result['action']) {
+        this.sendFailed(seq, 'need request param {action}');
+        return
+    }
+	action=result["action"]
+    var theHandler = this.handlers[action];
+    try {
+		if (!result["param"]){
+			theHandler(function (response) {
+				_this.sendResult(action, response);
+			})
+		}else{
+			theHandler(function (response) {
+				_this.sendResult(action, response);
+			},result["param"])
+		}
+		
+    } catch (e) {
+        console.log("error: " + e);
+        _this.sendResult(action+e);
+    }
+}
+
+Hlclient.prototype.sendResult = function (action, e) {
+    this.send(action + atob("aGxeX14") + e);
+}

+ 9 - 0
go.mod

@@ -0,0 +1,9 @@
+module rpc
+
+go 1.16
+
+require (
+	github.com/gin-gonic/gin v1.7.4
+	github.com/gorilla/websocket v1.4.2
+	github.com/unrolled/secure v1.0.9
+)

+ 60 - 0
go.sum

@@ -0,0 +1,60 @@
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
+github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
+github.com/gin-gonic/gin v1.7.4 h1:QmUZXrvJ9qZ3GfWvQ+2wnW/1ePrTEJqPKMYEU3lD/DM=
+github.com/gin-gonic/gin v1.7.4/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY=
+github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
+github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
+github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
+github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
+github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no=
+github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
+github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
+github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
+github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
+github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
+github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
+github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
+github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
+github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
+github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
+github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y=
+github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=
+github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
+github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
+github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
+github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
+github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
+github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
+github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
+github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
+github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
+github.com/unrolled/secure v1.0.9 h1:BWRuEb1vDrBFFDdbCnKkof3gZ35I/bnHGyt0LB0TNyQ=
+github.com/unrolled/secure v1.0.9/go.mod h1:fO+mEan+FLB0CdEnHf6Q4ZZVNqG+5fuLFnP8p0BXDPI=
+github.com/urfave/negroni v1.0.0 h1:kIimOitoypq34K7TG7DUaJ9kq/N4Ofuwi1sjz0KipXc=
+github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
+golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42 h1:vEOn+mP2zCOVzKckCZy6YsCtDblrpj/w7B9nxGNELpg=
+golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
+gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

+ 186 - 0
main.go

@@ -0,0 +1,186 @@
+package main
+
+import (
+	"fmt"
+	"github.com/gin-gonic/gin"
+	"github.com/gorilla/websocket"
+	"github.com/unrolled/secure"
+	"log"
+	"net/http"
+	"strings"
+	"sync"
+)
+//这里是普通http端口和ssl端口设置,随你改
+var Port=":12080"
+var sslPort = ":12443"
+
+
+//声明一个结构体 注入的ws就保存为结构体
+type Clients struct {
+	clientGroup string
+	clientName  string
+	//Data就是存方法的最新消息 用1个位置的管道来存
+	Data        map[string]chan string
+	clientWs    *websocket.Conn
+}
+
+var upGrader = websocket.Upgrader{
+	CheckOrigin: func(r *http.Request) bool { return true },
+}
+//存所有ws
+var hlClients sync.Map
+
+func NewClient(group string, name string, ws *websocket.Conn) *Clients {
+
+	client := &Clients{
+		clientGroup: group,
+		clientName:  name,
+		Data:        make(map[string]chan string, 1),
+
+		clientWs: ws,
+	}
+	return client
+
+}
+
+func ws(c *gin.Context) {
+	getGroup, getName := c.Query("group"), c.Query("name")
+	if getGroup == "" || getName == "" {
+		return
+	}
+	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
+	if err != nil {
+		log.Println("websocket err:", err)
+		return
+	}
+	client := NewClient(getGroup, getName, ws)
+
+	hlClients.Store(getGroup+"->"+getName, client)
+	for {
+		//读取ws中的数据
+		_, message, err := ws.ReadMessage()
+		if err != nil {
+			break
+		}
+		msg := string(message)
+
+
+		check := []uint8{104, 108, 94, 95, 94}
+
+		strIndex := strings.Index(msg, string(check))
+		if strIndex >= 1 {
+			action := msg[:strIndex]
+			//fmt.Println(action,"save msg")
+			if client.Data[action] == nil {
+				client.Data[action] = make(chan string, 1)
+
+			}
+			client.Data[action] <- msg[strIndex+5:]
+
+			//fmt.Println("go")
+
+			hlClients.Store(getGroup+"->"+getName, client)
+		} else {
+			fmt.Println(msg)
+		}
+
+	}
+	hlClients.Delete(getGroup + "->" + getName)
+	defer ws.Close()
+}
+
+func QueryFunc(client *Clients, funcName string, param string) {
+	var WriteDate string
+	if param == "" {
+		WriteDate = "{\"action\":\"" + funcName + "\"}"
+	} else {
+		WriteDate = "{\"action\":\"" + funcName + "\",\"param\":\"" + param + "\"}"
+	}
+	fmt.Println(WriteDate)
+	ws := client.clientWs
+	err := ws.WriteMessage(1, []byte(WriteDate))
+	if err != nil {
+		fmt.Println(err)
+	}
+
+}
+
+func Go(c *gin.Context) {
+	getGroup, getName, getAction, getParam := c.Query("group"), c.Query("name"), c.Query("action"), c.Query("param")
+	if getGroup == "" || getName == "" {
+		c.String(200, "input group and name")
+		return
+	}
+	//fmt.Println(getGroup, getName)
+	clientName, ok := hlClients.Load(getGroup + "->" + getName)
+
+	if ok == false {
+		c.String(200, "注入了ws?没有找到当前组和名字")
+		return
+	}
+	if getAction == "" {
+		c.JSON(200, gin.H{"group": getGroup, "name": getName})
+		return
+	}
+
+	value, ko := clientName.(*Clients)
+	if value.Data[getAction] == nil {
+		value.Data[getAction] = make(chan string, 1)
+	}
+
+	//执行发送函数
+
+	QueryFunc(value, getAction, getParam)
+
+
+	data := <-value.Data[getAction]
+
+	if ko {
+		c.JSON(200, gin.H{"status": "200", "group": value.clientGroup, "name": value.clientName, getAction: data})
+	} else {
+		c.JSON(666, gin.H{"message": "?"})
+	}
+
+}
+
+func getList(c *gin.Context) {
+	resList := "hliang:\r\n"
+	hlClients.Range(func(key, value interface{}) bool {
+		resList += key.(string) + "\r\n\t"
+		return true
+	})
+	c.String(200, resList)
+}
+
+func Home(c *gin.Context) {
+	c.String(200, "你好~")
+}
+func TlsHandler() gin.HandlerFunc {
+	return func(c *gin.Context) {
+		secureMiddleware := secure.New(secure.Options{
+			SSLRedirect: true,
+			SSLHost:     sslPort,
+		})
+		err := secureMiddleware.Process(c.Writer, c.Request)
+		if err != nil {
+			c.Abort()
+			return
+		}
+		c.Next()
+	}
+}
+
+func main() {
+	r := gin.Default()
+	r.GET("/", Home)
+	r.GET("/go", Go)
+	r.GET("/ws", ws)
+	r.GET("/list", getList)
+	r.Use(TlsHandler())
+	r.Run(Port)
+
+	//如果有https证书,请注释上面r.run那行,并把下面RunTls取消注释,设置pem和key为证书路径
+	//端口为12443
+	//r.RunTLS(sslPort, "zhengshu.pem", "zhengshu.key")
+
+}