gin.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/yaotian/gowechat"
  6. "github.com/yaotian/gowechat/mp/message"
  7. "github.com/yaotian/gowechat/wxcontext"
  8. )
  9. func main() {
  10. router := gin.Default()
  11. router.Any("/", hello)
  12. router.Run(":8001")
  13. }
  14. func hello(c *gin.Context) {
  15. //配置微信参数
  16. config := wxcontext.Config{
  17. AppID: "your app id",
  18. AppSecret: "your app secret",
  19. Token: "your token",
  20. EncodingAESKey: "your encoding aes key",
  21. }
  22. wc := gowechat.NewWechat(config)
  23. mp, err := wc.MpMgr()
  24. if err != nil {
  25. return
  26. }
  27. // 传入request和responseWriter
  28. msgHandler := mp.GetMsgHandler(c.Request, c.Writer)
  29. //设置接收消息的处理方法
  30. msgHandler.SetHandleMessageFunc(func(msg message.MixMessage) *message.Reply {
  31. //回复消息:演示回复用户发送的消息
  32. text := message.NewText(msg.Content)
  33. return &message.Reply{message.MsgTypeText, text}
  34. })
  35. //处理消息接收以及回复
  36. err = msgHandler.Handle()
  37. if err != nil {
  38. fmt.Println(err)
  39. return
  40. }
  41. //发送回复的消息
  42. msgHandler.Send()
  43. }