github.com/chanxuehong/wechat@v0.0.0-20230222024006-36f0325263cd/mp/core/example_test.go (about)

     1  package core_test
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/chanxuehong/wechat/mp/core"
     7  )
     8  
     9  func ExampleServer_ServeHTTP() {
    10  	mux := core.NewServeMux() // 创建 core.Handler, 也可以用自己实现的 core.Handler
    11  
    12  	// 注册消息(事件)处理 Handler, 都不是必须的!
    13  	{
    14  		mux.UseFunc(func(ctx *core.Context) { // 注册中间件, 处理所有的消息(事件)
    15  			// TODO: 中间件处理逻辑
    16  		})
    17  		mux.UseFuncForMsg(func(ctx *core.Context) { // 注册中间件, 处理所有的消息
    18  			// TODO: 中间件处理逻辑
    19  		})
    20  		mux.UseFuncForEvent(func(ctx *core.Context) { // 注册中间件, 处理所有的事件
    21  			// TODO: 中间件处理逻辑
    22  		})
    23  
    24  		mux.DefaultMsgHandleFunc(func(ctx *core.Context) { // 设置默认消息处理 Handler
    25  			// TODO: 消息处理逻辑
    26  		})
    27  		mux.DefaultEventHandleFunc(func(ctx *core.Context) { // 设置默认事件处理 Handler
    28  			// TODO: 事件处理逻辑
    29  		})
    30  
    31  		mux.MsgHandleFunc("{MsgType}", func(ctx *core.Context) { // 设置具体类型的消息处理 Handler
    32  			// TODO: 消息处理逻辑
    33  		})
    34  		mux.EventHandleFunc("{EventType}", func(ctx *core.Context) { // 设置具体类型的事件处理 Handler
    35  			// TODO: 事件处理逻辑
    36  		})
    37  	}
    38  
    39  	// 创建 Server, 设置正确的参数.
    40  	// 通常一个 Server 对应一个公众号, 当然一个 Server 也可以对应多个公众号, 这个时候 oriId 和 appId 都应该设置为空值!
    41  	srv := core.NewServer("{oriId}", "{appId}", "{token}", "{base64AESKey}", mux, nil)
    42  
    43  	// 在回调 URL 的 Handler 里处理消息(事件)
    44  	http.HandleFunc("/wechat_callback", func(w http.ResponseWriter, r *http.Request) {
    45  		srv.ServeHTTP(w, r, nil)
    46  	})
    47  }