add line webhook router
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
package line
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"io/ioutil"
|
||||
|
||||
"git.trj.tw/golang/mtgbot/modules/config"
|
||||
"git.trj.tw/golang/mtgbot/modules/context"
|
||||
"git.trj.tw/golang/mtgbot/modules/lineobj"
|
||||
)
|
||||
|
||||
// GetRawBody -
|
||||
func GetRawBody(c *context.Context) {
|
||||
byteBody, err := ioutil.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.DataFormat("body read fail")
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("rawbody", byteBody)
|
||||
c.Next()
|
||||
}
|
||||
|
||||
// VerifyLine -
|
||||
func VerifyLine(c *context.Context) {
|
||||
rawbody, ok := c.Get("rawbody")
|
||||
if !ok {
|
||||
c.DataFormat("body read fail")
|
||||
return
|
||||
}
|
||||
|
||||
var raw []byte
|
||||
if raw, ok = rawbody.([]byte); !ok {
|
||||
c.DataFormat("body type error")
|
||||
return
|
||||
}
|
||||
|
||||
sign := c.GetHeader("X-Line-Signature")
|
||||
if len(sign) == 0 {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
conf := config.GetConf()
|
||||
|
||||
hash := hmac.New(sha256.New, []byte(conf.Line.Secret))
|
||||
_, err := hash.Write(raw)
|
||||
if err != nil {
|
||||
c.ServerError(nil)
|
||||
return
|
||||
}
|
||||
|
||||
hashSign := base64.StdEncoding.EncodeToString(hash.Sum(nil))
|
||||
if hashSign != sign {
|
||||
c.CustomRes(403, map[string]string{
|
||||
"message": "sign verify fail",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
|
||||
// LineWebhook -
|
||||
func LineWebhook(c *context.Context) {
|
||||
rawbody, ok := c.Get("rawbody")
|
||||
if !ok {
|
||||
c.DataFormat("body read fail")
|
||||
return
|
||||
}
|
||||
|
||||
var raw []byte
|
||||
if raw, ok = rawbody.([]byte); !ok {
|
||||
c.DataFormat("body type error")
|
||||
return
|
||||
}
|
||||
|
||||
events := lineobj.ParseWebhookBody(raw)
|
||||
if events == nil {
|
||||
c.ServerError(nil)
|
||||
return
|
||||
}
|
||||
|
||||
if len(events.Events) > 0 {
|
||||
for _, v := range events.Events {
|
||||
go lineobj.MessageEvent(v)
|
||||
}
|
||||
}
|
||||
|
||||
c.Success(nil)
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
package routes
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
import (
|
||||
"git.trj.tw/golang/mtgbot/modules/context"
|
||||
"git.trj.tw/golang/mtgbot/router/line"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var r *gin.Engine
|
||||
|
||||
@@ -16,4 +20,8 @@ func SetRoutes(r *gin.Engine) {
|
||||
r.GET("/", func(c *gin.Context) {
|
||||
c.String(200, "Hello")
|
||||
})
|
||||
|
||||
r.POST("/line", context.PatchCtx(line.GetRawBody), context.PatchCtx(line.VerifyLine), context.PatchCtx(line.LineWebhook))
|
||||
r.POST("/line/", context.PatchCtx(line.GetRawBody), context.PatchCtx(line.VerifyLine), context.PatchCtx(line.LineWebhook))
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user