houyaf пре 3 година
родитељ
комит
9f9a0ede56

BIN
build/go_build_main_go.exe


+ 1 - 2
cmd/bootstrap/bootstrapper.go

@@ -14,8 +14,7 @@ type Bootstrapper struct {
 	AppName      string
 	AppOwner     string
 	AppSpawnDate time.Time
-
-	Sessions *sessions.Sessions
+	Sessions     *sessions.Sessions
 }
 
 func New(appName, appOwner string, cfgs ...Configurator) *Bootstrapper {

+ 1 - 54
cmd/file_server/minio.go → cmd/file_server/minio_client.go

@@ -8,7 +8,6 @@ import (
 	"github.com/minio/minio-go/v7/pkg/credentials"
 	"log"
 	"path"
-	"sync"
 )
 
 type MinioConfig struct {
@@ -18,36 +17,6 @@ type MinioConfig struct {
 	UseSSL    bool   `json:"useSSL"`
 }
 
-var defaultConfig = &MinioConfig{
-	EndPoint:  "114.116.19.14:9000",
-	AccessKey: "root",
-	SecretKey: "Houyaf1!",
-	UseSSL:    false,
-}
-
-var (
-	minioServerPool   *sync.Pool
-	defaultFileBucket = "file"
-	defaultIconBucket = "icon"
-	defaultLocation   = "us-east-1"
-)
-
-type DestFile struct {
-	FileName     string
-	FileUrl      string
-	FileSize     int64
-	FileExt      string
-	FileMimeType string
-}
-
-func init() {
-	minioServerPool = &sync.Pool{
-		New: func() interface{} {
-			return &MinioServe{}
-		},
-	}
-}
-
 func (c *MinioConfig) validate() error {
 	if c.EndPoint == "" {
 		return errors.New("EndPoint host not specified")
@@ -77,6 +46,7 @@ func (c *MinioConfig) getClient() (*minio.Client, error) {
 
 	if err != nil {
 		log.Fatalf("connect minio server fail %s url %s", err.Error(), c.EndPoint)
+		return nil, err
 	}
 	return minioClient, nil
 }
@@ -149,26 +119,3 @@ func (m *MinioServe) uploadFile(objectName, filePath string) (*DestFile, error)
 
 	return targetFile, nil
 }
-
-func acquireMinioServer() *MinioServe {
-	return minioServerPool.Get().(*MinioServe)
-}
-
-func releaseMinioServer(m *MinioServe) {
-	m.Reset()
-	minioServerPool.Put(m)
-}
-
-func UploadFileToMinio(fileName, filePath string) (*DestFile, error) {
-	m := acquireMinioServer()
-
-	client, err := defaultConfig.getClient()
-	if err != nil {
-		return nil, err
-	}
-	defer func() {
-		releaseMinioServer(m)
-	}()
-	m.Client = client
-	return m.uploadFile(fileName, filePath)
-}

+ 64 - 0
cmd/file_server/minio_cmd.go

@@ -0,0 +1,64 @@
+package file_server
+
+import (
+	"errors"
+	"log"
+	"sync"
+)
+
+var ErrMinioInit = errors.New("MINIO初始化失败")
+
+var (
+	minioServerPool   *sync.Pool
+	defaultFileBucket = "file"
+	defaultIconBucket = "icon"
+	defaultLocation   = "us-east-1"
+)
+
+var defaultConfig = &MinioConfig{
+	EndPoint:  "114.116.19.14:9000",
+	AccessKey: "root",
+	SecretKey: "Houyaf1!",
+	UseSSL:    false,
+}
+
+func init() {
+	minioServerPool = &sync.Pool{
+		New: func() interface{} {
+			return &MinioServe{}
+		},
+	}
+}
+
+type DestFile struct {
+	FileName     string
+	FileUrl      string
+	FileSize     int64
+	FileExt      string
+	FileMimeType string
+}
+
+func acquireMinioServer() *MinioServe {
+	return minioServerPool.Get().(*MinioServe)
+}
+
+func releaseMinioServer(m *MinioServe) {
+	m.Reset()
+	minioServerPool.Put(m)
+}
+
+func UploadFileToMinio(fileName, filePath string) (*DestFile, error) {
+	m := acquireMinioServer()
+
+	client, err := defaultConfig.getClient()
+	if err != nil {
+		log.Fatal(ErrMinioInit)
+		return nil, err
+	}
+	defer func() {
+		releaseMinioServer(m)
+	}()
+
+	m.Client = client
+	return m.uploadFile(fileName, filePath)
+}

+ 140 - 0
cmd/mqtt/mqtt_client.go

@@ -0,0 +1,140 @@
+package mqttclient
+
+import (
+	"crypto/tls"
+	"errors"
+	"fmt"
+	mqtt "github.com/eclipse/paho.mqtt.golang"
+	"log"
+	"time"
+)
+
+// MqttConnectConfig 连接的相关配置
+type MqttConnectConfig struct {
+	Broker           string
+	User             string
+	Password         string
+	Certificate      string //证书文件
+	PrivateKey       string //秘钥
+	ClientId         string
+	WillEnabled      bool   //遗愿
+	WillTopic        string //遗愿主题
+	WillPayload      string //遗愿消息
+	WillQos          byte   //遗愿服务质量
+	Qos              byte   //服务质量
+	Retained         bool   //保留消息
+	OnConnect        mqtt.OnConnectHandler
+	OnConnectionLost mqtt.ConnectionLostHandler
+}
+
+// MqttClient MQTT客户端,此外也包含了几个参数
+type MqttClient struct {
+	qos      byte
+	retained bool
+	Client   mqtt.Client
+	topics   map[string]mqtt.MessageHandler
+}
+
+// 新建证书,也可以不用
+func newTLSConfig(certFile string, privateKey string) (*tls.Config, error) {
+	cert, err := tls.LoadX509KeyPair(certFile, privateKey)
+	if err != nil {
+		return nil, err
+	}
+	return &tls.Config{
+		ClientAuth:         tls.NoClientCert, //不需要证书
+		ClientCAs:          nil,              //不验证证书
+		InsecureSkipVerify: true,             //接受服务器提供的任何证书和该证书中的任何主机名
+		Certificates:       []tls.Certificate{cert},
+	}, nil
+}
+
+func NewMqttClient(config MqttConnectConfig) *MqttClient {
+	var c MqttClient
+	opts := mqtt.NewClientOptions().AddBroker(config.Broker).SetClientID(config.ClientId).SetMaxReconnectInterval(time.Second * 5)
+	if config.WillEnabled {
+		opts.SetWill(config.WillTopic, config.WillPayload, config.WillQos, config.Retained)
+	}
+	//判断是否设置证书
+	if config.Certificate != "" {
+		tlsConfig, err := newTLSConfig(config.Certificate, config.PrivateKey)
+		if err != nil {
+			log.Panic(err)
+			return nil
+		}
+		opts.SetTLSConfig(tlsConfig)
+	} else {
+		opts.SetUsername(config.User).SetPassword(config.Password)
+	}
+	//初始化
+	if config.OnConnect == nil {
+		config.OnConnect = func(c mqtt.Client) {}
+	}
+	if config.OnConnectionLost == nil {
+		config.OnConnectionLost = func(c mqtt.Client, err error) {}
+	}
+	opts.SetOnConnectHandler(c.connectHandler(config.OnConnect)).SetConnectionLostHandler(c.onConnectionLostHandler(config.OnConnectionLost))
+	c.Client = mqtt.NewClient(opts)
+	c.qos = config.Qos                              // qos的级别
+	c.retained = config.Retained                    // 保留消息
+	c.topics = make(map[string]mqtt.MessageHandler) //topic
+	// 用token的状态判断
+	if tc := c.Client.Connect(); tc.Wait() && tc.Error() != nil {
+		log.Panic(tc.Error())
+		return nil
+	}
+	return &c
+}
+
+// Publish  Mqtt message.
+func (mc *MqttClient) Publish(topic string, payload []byte) error {
+	if mc != nil && mc.Client.IsConnected() {
+		if tc := mc.Client.Publish(topic, mc.qos, mc.retained, payload); tc.Wait() && tc.Error() != nil {
+			return tc.Error()
+		}
+		return nil
+	}
+	return errors.New("mqttClient is nil or disconnected")
+}
+
+// Subscribe subscribe a Mqtt topic.
+func (mc *MqttClient) Subscribe(topics []string, onMessage mqtt.MessageHandler) error {
+	for _, topic := range topics {
+		if tc := mc.Client.Subscribe(topic, mc.qos, onMessage); tc.Wait() && tc.Error() != nil {
+			return tc.Error()
+		}
+		mc.topics[topic] = onMessage
+		log.Println(fmt.Sprintf("订阅主题[%s]成功", topic))
+	}
+	return nil
+}
+
+// Unsubscribe unsubscribe a Mqtt topic.
+func (mc *MqttClient) Unsubscribe(topics ...string) error {
+	if tc := mc.Client.Unsubscribe(topics...); tc.Wait() && tc.Error() != nil {
+		return tc.Error()
+	}
+	for _, topic := range topics {
+		delete(mc.topics, topic)
+	}
+	return nil
+}
+
+func (mc *MqttClient) Close() {
+	mc.Client.Disconnect(250) //Millisecond
+}
+
+func (mc *MqttClient) connectHandler(handler mqtt.OnConnectHandler) mqtt.OnConnectHandler {
+	return func(c mqtt.Client) {
+		for topic, onMessage := range mc.topics {
+			mc.Client.Subscribe(topic, mc.qos, onMessage)
+		}
+		handler(c)
+	}
+}
+
+func (mc *MqttClient) onConnectionLostHandler(handler mqtt.ConnectionLostHandler) mqtt.ConnectionLostHandler {
+	return func(c mqtt.Client, e error) {
+		handler(c, e)
+	}
+}

+ 57 - 0
cmd/mqtt/mqtt_cmd.go

@@ -0,0 +1,57 @@
+package mqttclient
+
+import (
+	"errors"
+	mqtt "github.com/eclipse/paho.mqtt.golang"
+	"log"
+	"sync"
+)
+
+var CONFIG = MqttConnectConfig{
+	Broker:           "tcp://1.15.92.205:1883",
+	User:             "admin",
+	Password:         "houyaf1!",
+	Certificate:      "",
+	PrivateKey:       "",
+	ClientId:         "clientID",
+	WillEnabled:      false,
+	WillTopic:        "",
+	WillPayload:      "",
+	WillQos:          0,
+	Qos:              0,
+	Retained:         false,
+	OnConnect:        nil,
+	OnConnectionLost: nil,
+}
+
+var ErrMqttInit = errors.New("MQTT初始化失败")
+
+var (
+	once       sync.Once
+	mqttClient *MqttClient
+)
+
+func Instance() *MqttClient {
+	once.Do(func() {
+		mqttClient = NewMqttClient(CONFIG)
+	})
+	return mqttClient
+}
+
+func init() {
+	if Instance() == nil {
+		log.Fatal(ErrMqttInit)
+	}
+}
+
+func Publish(topic string, payload []byte) error {
+	return Instance().Publish(topic, payload)
+}
+
+func Subscribe(topics []string, onMessage mqtt.MessageHandler) error {
+	return Instance().Subscribe(topics, onMessage)
+}
+
+func Unsubscribe(topics ...string) error {
+	return Instance().Unsubscribe(topics...)
+}

+ 2 - 0
go.mod

@@ -27,6 +27,7 @@ require (
 	github.com/cespare/xxhash/v2 v2.1.2 // indirect
 	github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
 	github.com/dustin/go-humanize v1.0.1 // indirect
+	github.com/eclipse/paho.mqtt.golang v1.4.2 // indirect
 	github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385 // indirect
 	github.com/fatih/structs v1.1.0 // indirect
 	github.com/flosch/pongo2/v4 v4.0.2 // indirect
@@ -77,6 +78,7 @@ require (
 	github.com/yosssi/ace v0.0.5 // indirect
 	golang.org/x/crypto v0.9.0 // indirect
 	golang.org/x/net v0.10.0 // indirect
+	golang.org/x/sync v0.1.0 // indirect
 	golang.org/x/sys v0.8.0 // indirect
 	golang.org/x/text v0.9.0 // indirect
 	golang.org/x/time v0.3.0 // indirect