Awesome
Lark Hertz
Hertz middleware for go-lark.
Middlewares
LarkChallengeHandler
: URL challenge for general events and card callbackLarkEventHandler
: Event v2 (schema 2.0)LarkCardHandler
: Card callbackLarkMessageHandler
: (Legacy) Incoming message event (schema 1.0)
Installation
go get -u github.com/go-lark/lark-hertz
Usage
package main
import (
"context"
"fmt"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
larkhertz "github.com/go-lark/lark-hertz"
)
func main() {
r := server.Default()
middleware := larkhertz.NewLarkMiddleware()
// lark server challenge
r.Use(middleware.LarkChallengeHandler())
// all supported events
eventGroup := r.Group("/event")
{
eventGroup.Use(middleware.LarkEventHandler())
eventGroup.POST("/", func(c context.Context, ctx *app.RequestContext) {
if event, ok := middleware.GetEvent(ctx); ok { // => returns `*lark.EventV2`
}
})
}
// card callback only
cardGroup := r.Group("/card")
{
cardGroup.Use(middleware.LarkCardHandler())
cardGroup.POST("/callback", func(c context.Context, ctx *app.RequestContext) {
if card, ok := middleware.GetCardCallback(ctx); ok { // => returns `*lark.EventCardCallback`
}
})
}
r.Spin()
}
Event v2
The default mode is event v1. However, Lark has provided event v2 and it applied automatically to newly created bots.
To enable EventV2, we use LarkEventHandler
instead of LarkMessageHandler
:
r.Use(middleware.LarkEventHandler())
Get the event (e.g. Message):
r.POST("/", func(c context.Context, ctx *app.RequestContext) {
if event, ok := middleware.GetEvent(ctx); ok { // => GetEvent instead of GetMessage
if evt.Header.EventType == lark.EventTypeMessageReceived {
if msg, err := evt.GetMessageReceived(); err == nil {
fmt.Println(msg.Message.Content)
}
// you may have to parse other events
}
}
})
Card Callback
We may also setup callback for card actions (e.g. button). The URL challenge part is the same.
We may use LarkCardHandler
to handle the actions:
r.Use(middleware.LarkCardHandler())
r.POST("/", func(c context.Context, ctx *app.RequestContext) {
if event, ok = middleware.GetCardCallback(ctx); ok {
}
})
Token Verification
middleware.WithTokenVerfication("asodjiaoijoi121iuhiaud")
Encryption
Notice: encryption is not available for card callback, due to restriction from Lark Open Platform.
middleware.WithEncryption("1231asda")
URL Binding
Only bind specific URL for events:
middleware.BindURLPrefix("/abc")
About
Copyright (c) go-lark Developers, 2018-2024.