-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
79 lines (67 loc) · 2.11 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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/clightning4j/lnsocket-function/lnsocket"
"github.com/gin-gonic/gin"
)
type Request struct {
NodeID string `json:"node_id"`
Address string `json:"host"`
Rune string `json:"rune"`
Method string `json:"method"`
Params map[string]any `json:"params"`
}
func PostMethod(c *gin.Context) {
jsonData, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, fmt.Sprintf("Error: %s", err))
return
}
var req Request
if err := json.Unmarshal(jsonData, &req); err != nil {
c.JSON(http.StatusInternalServerError, fmt.Sprintf("Error: %s", err))
return
}
client := lnsocket.New(req.NodeID, req.Address)
defer client.Disconnect()
if err := client.Connect(); err != nil {
c.JSON(http.StatusInternalServerError, fmt.Sprintf("Error: %s", err))
return
}
response, err := client.Call(req.Method, req.Params, req.Rune)
if err != nil {
c.JSON(http.StatusInternalServerError, fmt.Sprintf("Error: %s", err))
return
}
c.JSON(http.StatusOK, response)
}
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Credentials", "true")
c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Header("Access-Control-Allow-Methods", "POST,HEAD,PATCH, OPTIONS, GET, PUT")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
func main() {
router := gin.Default()
// Source https://stackoverflow.com/a/54802142/10854225
router.Use(CORSMiddleware())
router.POST("/lnsocket", PostMethod)
router.GET("/welcome", func(c *gin.Context) {
firstname := c.DefaultQuery("firstname", "Guest")
lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")
c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
})
listenPort := "9002"
// Listen and Server on the LocalHost:Port
router.Run(":" + listenPort)
}