packages/middlewares/logger/logger_test.go
2025-06-13 17:18:52 +08:00

60 lines
1.0 KiB
Go

package logger
import (
"errors"
"github.com/gin-gonic/gin"
"net/http"
"testing"
"time"
)
func TestLogger(t *testing.T) {
gin.SetMode(gin.TestMode)
app := gin.New()
app.Use(New())
app.GET("/200", func(c *gin.Context) {
c.JSON(200, gin.H{"hello": "world"})
})
app.GET("/400", func(c *gin.Context) {
c.JSON(400, gin.H{"hello": "world"})
})
app.GET("/500", func(c *gin.Context) {
c.JSON(500, gin.H{"hello": "world"})
})
ok := make(chan struct{})
svc := http.Server{
Handler: app,
Addr: "127.0.0.1:8080",
}
go func() {
ok <- struct{}{}
if err := svc.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
t.Error(err)
}
}()
<-ok
time.Sleep(200 * time.Millisecond)
justErr := func(_ any, e error) error {
return e
}
err := errors.Join(
justErr(http.Get("http://127.0.0.1:8080/200")),
justErr(http.Get("http://127.0.0.1:8080/400")),
justErr(http.Get("http://127.0.0.1:8080/500")),
)
if err != nil {
t.Error(err)
}
err = svc.Shutdown(t.Context())
if err != nil {
t.Error(err)
}
}