github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/ginx/hlog/hlog_test.go (about) 1 package hlog_test 2 3 import ( 4 "io/ioutil" 5 "net/http" 6 "testing" 7 8 "github.com/bingoohuang/gg/pkg/ginx/adapt" 9 "github.com/bingoohuang/gg/pkg/ginx/anyfn" 10 "github.com/bingoohuang/gg/pkg/ginx/gintest" 11 "github.com/bingoohuang/gg/pkg/ginx/hlog" 12 "github.com/bingoohuang/gg/pkg/sqx" 13 "github.com/bingoohuang/golog" 14 "github.com/bingoohuang/golog/pkg/ginlogrus" 15 "github.com/gin-gonic/gin" 16 _ "github.com/go-sql-driver/mysql" 17 "github.com/stretchr/testify/assert" 18 ) 19 20 func init() { 21 golog.Setup() 22 gin.SetMode(gin.ReleaseMode) 23 } 24 25 func TestLogger(t *testing.T) { 26 af := anyfn.NewAdapter() 27 hf := hlog.NewAdapter(hlog.NewLogrusStore()) 28 r := adapt.Adapt(gin.New(), af, hf) 29 r.Use(ginlogrus.Logger(nil, true)) 30 31 r.POST("/hello", af.F(func() string { return "Hello hello!" }), hf.F(hf.Biz("你好啊"))) 32 r.POST("/world", af.F(func() string { return "Hello world!" })) 33 r.POST("/bye", af.F(func() string { return "Hello bye!" }), hf.F(hf.Ignore())) 34 35 // r.Run(":8080") 36 37 rr := gintest.Post("/hello", r) 38 assert.Equal(t, "Hello hello!", rr.Body()) 39 40 rr = gintest.Post("/world", r) 41 assert.Equal(t, "Hello world!", rr.Body()) 42 43 rr = gintest.Post("/bye", r) 44 assert.Equal(t, "Hello bye!", rr.Body()) 45 } 46 47 const DSN = `root:root@tcp(127.0.0.1:3306)/httplog?charset=utf8mb4&parseTime=true&loc=Local` 48 49 func TestNewSQLStore(t *testing.T) { 50 _, db, err := sqx.Open("mysql", DSN) 51 assert.Nil(t, err) 52 53 af := anyfn.NewAdapter() 54 hf := hlog.NewAdapter(hlog.NewSQLStore(db, "biz_log")) 55 r := adapt.Adapt(gin.New(), af, hf) 56 r.Use(ginlogrus.Logger(nil, true)) 57 r.Use(func(c *gin.Context) { 58 hlog.PutAttr(c, "age", 5000) 59 }) 60 61 r.POST("/hello", af.F(handleIndex), hf.F(hf.Biz("回显处理hlog"))) 62 r.POST("/world", af.F(func() string { return "Hello world!" }), hf.F(hf.Biz("世界你好"))) 63 64 rr := gintest.Post("/hello", r, gintest.JSONVar(`{"name":"dingding"}`)) 65 assert.Equal(t, `{"name":"dingding"}`, rr.Body()) 66 67 gintest.Post("/world", r) 68 } 69 70 // simplest possible server that returns url as plain text. 71 func handleIndex(w http.ResponseWriter, r *http.Request, c *gin.Context) { 72 // msg := fmt.Sprintf("You've called url %s", r.URL.String()) 73 w.Header().Set("Content-Type", "text/plain") 74 w.WriteHeader(http.StatusOK) // 200 75 76 hlog.PutAttr(c, "xxx", "yyy") 77 hlog.PutAttrMap(c, hlog.Attrs{"name": "alice", "female": true}) 78 79 var bytes []byte 80 81 if r.Body != nil { 82 bytes, _ = ioutil.ReadAll(r.Body) 83 } else { 84 bytes = []byte(`empty request body`) 85 } 86 87 _, _ = w.Write(bytes) 88 }