gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
77.77k stars 7.96k forks source link

Gin minimum execution time #3782

Open Gadrawingz opened 9 months ago

Gadrawingz commented 9 months ago

As of PHP framework like Codeigniter, Is that possible in Gin

How to reproduce

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    g := gin.Default()
    g.GET("/hello/:name", func(c *gin.Context) {
        c.String(200, "Hello %s", c.Param("name"))
    })
    g.Run(":9000")
}

Expectations

Environment

sxk10812139 commented 9 months ago

Perhaps you meant this?

startTime := time.Now()
...
endTime := time.Now()
ivanruslimcdohl commented 9 months ago
package main

import (
    "log"
    "time"
)

func main() {
    tStart := time.Now()
    time.Sleep(123 * time.Millisecond)
    execTime := time.Since(tStart)

    log.Printf("executed in %s\n, ", execTime)
}

If you want it in gin Middleware

package main

import (
    "log"
    "time"

    "github.com/gin-gonic/gin"
)

func main() {
    g := gin.Default()
    g.Use(roundTrip())
    g.GET("/hello/:name", func(c *gin.Context) {
        c.String(200, "Hello %s", c.Param("name"))
    })
    g.Run(":9000")
}

func roundTrip() gin.HandlerFunc {
    return func(c *gin.Context) {
        tsReq := time.Now()

        c.Next()

        execTime := time.Since(tsReq)
        log.Printf("%s executed in %s\n, ", c.FullPath(), execTime)
    }
}

Anyway, the default logger in Gin already print out the execution time.

Gadrawingz commented 9 months ago

I am starting to understand!