github.com/wfusion/gofusion@v1.1.14/http/consts/context.go (about)

     1  package consts
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/gin-gonic/gin"
     7  	"github.com/spf13/cast"
     8  )
     9  
    10  const (
    11  	ctxReqStartAtKey = "http:req_start_at"
    12  	ctxReqCostKey    = "http:req_cost"
    13  )
    14  
    15  func SetReqStartTime(c *gin.Context) {
    16  	c.Set(ctxReqStartAtKey, time.Now())
    17  }
    18  
    19  func GetReqCost(c *gin.Context) time.Duration {
    20  	if cost, ok := c.Get(ctxReqCostKey); ok {
    21  		return cast.ToDuration(cost)
    22  	}
    23  
    24  	start := time.Now()
    25  	if _, ok := c.Get(ctxReqStartAtKey); ok {
    26  		start = c.GetTime(ctxReqStartAtKey)
    27  	}
    28  	cost := time.Since(start)
    29  	c.Set(ctxReqCostKey, cost)
    30  	return cost
    31  }