-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
183 lines (162 loc) · 4.34 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package main
import (
"github.com/eclipse/paho.mqtt.golang"
"github.com/gin-gonic/gin"
"github.com/urfave/cli"
"log"
"net/http"
"os"
)
// Configuration Structure to Hold the Config Values
type Configuration struct {
MqttServerURL string
MqttUsername string
MqttPassword string
BasicAuthUser string
BasicAuthPass string
GinPort string
}
// Container Structure to Hold both Config and MQTTClient
type Container struct {
Config Configuration
MqttClient mqtt.Client
}
// PublishDTO is the sample data transfer object for publish http route
type PublishDTO struct {
Topic string `binding:"required" json:"topic"`
Message string `binding:"required" json:"message"`
}
func main() {
app := cli.NewApp()
app.Name = "HTTP-MQTT Bridge"
app.Usage = "Makes a bridge from HTTP to MQTT"
app.Action = func(c *cli.Context) error {
cli.ShowAppHelp(c)
return nil
}
app.Commands = []cli.Command{
{
Name: "start",
Aliases: []string{"s"},
Usage: "starts the server",
Flags: []cli.Flag{
cli.StringFlag{
Name: "mqtt-host, mh",
Value: "tcp://localhost:1883",
Usage: "MQTT Host Address",
EnvVar: "MQTT_HOST",
},
cli.StringFlag{
Name: "mqtt-user,mu",
Value: "",
Usage: "MQTT Host Username",
EnvVar: "MQTT_USER",
},
cli.StringFlag{
Name: "mqtt-pass,mp",
Value: "",
Usage: "MQTT Host Password",
EnvVar: "MQTT_PASS",
},
cli.StringFlag{
Name: "username,u",
Value: "alikaviani",
Usage: "Basic Authentication Username",
EnvVar: "AUTH_USERNAME",
},
cli.StringFlag{
Name: "password,p",
Value: "F#@{fW+/",
Usage: "Basic Authentication Password",
EnvVar: "AUTH_PASSWORD",
},
cli.StringFlag{
Name: "port",
Value: "8090",
Usage: "GIN Router Port",
EnvVar: "PORT",
},
},
Action: func(c *cli.Context) error {
// Fills the Configuration
container := InitializeContainer(c)
// Setup Gin Server + MQTT
Setup(container)
return nil
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
// InitializeContainer Create the container with provided cli config values
func InitializeContainer(c *cli.Context) *Container {
container := new(Container)
container.Config = Configuration{
MqttServerURL: c.String("mqtt-host"),
MqttUsername: c.String("mqtt-user"),
MqttPassword: c.String("mqtt-pass"),
BasicAuthUser: c.String("username"),
BasicAuthPass: c.String("password"),
GinPort: c.String("port"),
}
return container
}
// Setup Wraps the Whole Setup Process
func Setup(container *Container) {
// Connect to MQTT Client
SetupMQTT(container)
// Setup GIN
r := SetupGin(container)
// Run Gin Server
r.Run(":" + container.Config.GinPort)
}
// SetupMQTT Creates the MQTT Connection and stores it in Container
func SetupMQTT(container *Container) {
opts := mqtt.NewClientOptions().AddBroker(container.Config.MqttServerURL)
if container.Config.MqttUsername != "" {
opts.Username = container.Config.MqttUsername
opts.Password = container.Config.MqttPassword
}
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Fatal("MQTT Error: ", token.Error())
}
container.MqttClient = client
}
// SetupGin Creates the Gin Router
func SetupGin(container *Container) *gin.Engine {
r := gin.Default()
// Ping Test
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong")
})
// Ping Test
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "i am ready !")
})
authorized := r.Group("/", gin.BasicAuth(gin.Accounts{
container.Config.BasicAuthUser: container.Config.BasicAuthPass, // user:foo password:bar
}))
// Post To Topic
authorized.POST("publish", func(c *gin.Context) {
var publishDTO PublishDTO
// Validate Payloadd
if err := c.ShouldBindJSON(&publishDTO); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": err.Error()})
return
}
// Go For MQTT Publish
client := container.MqttClient
if token := client.Publish(publishDTO.Topic, 0, false, publishDTO.Message); token.Error() != nil {
// Return Error
log.Println("Error:", token.Error())
c.JSON(http.StatusFailedDependency, gin.H{"status": "error", "error": token.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
return r
}