-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.go
122 lines (98 loc) · 2.31 KB
/
module.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
package module
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"github.com/gin-gonic/gin"
"github.com/homescreenrocks/homescreen/shared"
)
type Module struct {
shared.Module
RouteSetup RouteSetup
}
func (p *Module) Main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s <core-url>\n", os.Args[0])
os.Exit(2)
}
err := p.run(os.Args[1])
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to start module.\n")
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func (m *Module) run(coreUrl string) error {
log.Printf("Starting module for homescreen using the module helper.")
log.Printf(" ID: %s", m.Metadata.ID)
log.Printf(" Name: %s", m.Metadata.Name)
log.Printf(" Version: %s", m.Metadata.Version)
log.Printf(" Description: %s", m.Metadata.Description)
engine, err := m.setupGin()
if err != nil {
return err
}
listner, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return fmt.Errorf("Failed started HTTP listener: %v", err)
}
err = m.register(coreUrl, "http://"+listner.Addr().String())
if err != nil {
return fmt.Errorf("Failed server HTTP: %v", err)
}
fmt.Println("Server listens on: ", listner.Addr().String())
err = http.Serve(listner, engine)
if err != nil {
return fmt.Errorf("Failed server HTTP: %v", err)
}
return nil
}
func (p *Module) setupGin() (*gin.Engine, error) {
gin.SetMode(gin.ReleaseMode)
m := gin.Default()
if p.RouteSetup != nil {
err := p.RouteSetup(m.Group("/module"))
if err != nil {
return nil, err
}
m.GET("/hello", helloMessage)
}
//v1 := m.Group("/v1")
return m, nil
}
func (p *Module) register(coreUrl string, moduleUrl string) error {
req := &shared.Module{
ModuleURL: moduleUrl,
Metadata: p.Metadata,
Settings: p.Settings,
}
data, err := json.Marshal(req)
if err != nil {
return err
}
buf := bytes.NewBuffer(data)
resp, err := http.Post(
fmt.Sprintf("%s/api/v1/modules/", coreUrl),
"application/json", buf)
if err != nil {
return err
}
if resp.StatusCode != 200 {
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf("unexpected response code %d: %s", resp.StatusCode, string(data))
}
return nil
}
func helloMessage(c *gin.Context) {
c.JSON(200, gin.H{
"message": "IamAlive",
})
}