mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-15 04:57:07 +08:00
Merge 6f7c7fc4e5faa3fabb20a1ab70b3bfec45a53fd1 into f97326307220d823189d5877cca9d18f35dd5c5a
This commit is contained in:
commit
0009327c56
@ -286,6 +286,10 @@ func Logger() gin.HandlerFunc {
|
|||||||
// after request
|
// after request
|
||||||
latency := time.Since(t)
|
latency := time.Since(t)
|
||||||
log.Print(latency)
|
log.Print(latency)
|
||||||
|
|
||||||
|
// access the status we are sending
|
||||||
|
status := c.Writer.Status()
|
||||||
|
log.Println(status)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
82
examples/logging/example_ansi.go
Normal file
82
examples/logging/example_ansi.go
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/mgutz/ansi"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
white = ansi.ColorCode("white+h:black")
|
||||||
|
red = ansi.ColorCode("red+h:black")
|
||||||
|
green = ansi.ColorCode("green+h:black")
|
||||||
|
yellow = ansi.ColorCode("yellow+h:black")
|
||||||
|
blue = ansi.ColorCode("blue+h:black")
|
||||||
|
reset = ansi.ColorCode("reset")
|
||||||
|
)
|
||||||
|
|
||||||
|
//
|
||||||
|
// Example of an extended ansi-colored logger using the
|
||||||
|
// ctx.Writer.Status() function
|
||||||
|
func logger(c *gin.Context) {
|
||||||
|
start := time.Now()
|
||||||
|
|
||||||
|
// save the IP of the requester
|
||||||
|
requester := c.Req.Header.Get("X-Real-IP")
|
||||||
|
|
||||||
|
// if the requester-header is empty, check the forwarded-header
|
||||||
|
if requester == "" {
|
||||||
|
requester = c.Req.Header.Get("X-Forwarded-For")
|
||||||
|
}
|
||||||
|
|
||||||
|
// if the requester is still empty, use the hard-coded address from the socket
|
||||||
|
if requester == "" {
|
||||||
|
requester = c.Req.RemoteAddr
|
||||||
|
}
|
||||||
|
|
||||||
|
// ... finally, log the fact we got a request
|
||||||
|
log.Printf("<-- %16s | %6s | %s\n", requester, c.Req.Method, c.Req.URL.Path)
|
||||||
|
|
||||||
|
c.Next()
|
||||||
|
|
||||||
|
var color string
|
||||||
|
if code := c.Writer.Status(); code >= 200 && code <= 299 {
|
||||||
|
color = green
|
||||||
|
} else if code >= 300 && code <= 399 {
|
||||||
|
color = white
|
||||||
|
} else if code >= 400 && code <= 499 {
|
||||||
|
color = yellow
|
||||||
|
} else {
|
||||||
|
color = red
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("--> %s%16s | %6d | %s | %s%s\n",
|
||||||
|
color,
|
||||||
|
requester, c.Writer.Status(), time.Since(start), c.Req.URL.Path,
|
||||||
|
reset,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
r := gin.New()
|
||||||
|
r.Use(gin.Recovery())
|
||||||
|
r.Use(logger)
|
||||||
|
// or modify func.logger to return a handler and use:
|
||||||
|
// r.Use(logger())
|
||||||
|
|
||||||
|
// Ping test
|
||||||
|
r.GET("/:code", func(c *gin.Context) {
|
||||||
|
asInt, err := strconv.ParseInt(c.Params.ByName("code"), 10, 32)
|
||||||
|
if err != nil {
|
||||||
|
c.String(400, err.Error())
|
||||||
|
} else {
|
||||||
|
c.String(int(asInt), c.Params.ByName("code"))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Listen and Server in 0.0.0.0:8080
|
||||||
|
r.Run(":8081")
|
||||||
|
}
|
22
gin.go
22
gin.go
@ -35,7 +35,7 @@ type (
|
|||||||
// manage the flow, validate the JSON of a request and render a JSON response for example.
|
// manage the flow, validate the JSON of a request and render a JSON response for example.
|
||||||
Context struct {
|
Context struct {
|
||||||
Req *http.Request
|
Req *http.Request
|
||||||
Writer http.ResponseWriter
|
Writer ResponseWriter
|
||||||
Keys map[string]interface{}
|
Keys map[string]interface{}
|
||||||
Errors ErrorMsgs
|
Errors ErrorMsgs
|
||||||
Params httprouter.Params
|
Params httprouter.Params
|
||||||
@ -101,7 +101,7 @@ func (engine *Engine) handle404(w http.ResponseWriter, req *http.Request) {
|
|||||||
handlers := engine.combineHandlers(engine.handlers404)
|
handlers := engine.combineHandlers(engine.handlers404)
|
||||||
c := engine.createContext(w, req, nil, handlers)
|
c := engine.createContext(w, req, nil, handlers)
|
||||||
if engine.handlers404 == nil {
|
if engine.handlers404 == nil {
|
||||||
http.NotFound(c.Writer, c.Req)
|
http.NotFound(&c.Writer, c.Req)
|
||||||
} else {
|
} else {
|
||||||
c.Writer.WriteHeader(404)
|
c.Writer.WriteHeader(404)
|
||||||
}
|
}
|
||||||
@ -125,7 +125,7 @@ func (engine *Engine) ServeFiles(path string, root http.FileSystem) {
|
|||||||
|
|
||||||
// ServeHTTP makes the router implement the http.Handler interface.
|
// ServeHTTP makes the router implement the http.Handler interface.
|
||||||
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||||
engine.router.ServeHTTP(w, req)
|
engine.router.ServeHTTP(&ResponseWriter{w, -1}, req)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (engine *Engine) Run(addr string) {
|
func (engine *Engine) Run(addr string) {
|
||||||
@ -140,7 +140,7 @@ func (engine *Engine) Run(addr string) {
|
|||||||
|
|
||||||
func (group *RouterGroup) createContext(w http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {
|
func (group *RouterGroup) createContext(w http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {
|
||||||
return &Context{
|
return &Context{
|
||||||
Writer: w,
|
Writer: ResponseWriter{w, StatusUnset},
|
||||||
Req: req,
|
Req: req,
|
||||||
index: -1,
|
index: -1,
|
||||||
engine: group.engine,
|
engine: group.engine,
|
||||||
@ -180,7 +180,7 @@ func (group *RouterGroup) Handle(method, p string, handlers []HandlerFunc) {
|
|||||||
p = path.Join(group.prefix, p)
|
p = path.Join(group.prefix, p)
|
||||||
handlers = group.combineHandlers(handlers)
|
handlers = group.combineHandlers(handlers)
|
||||||
group.engine.router.Handle(method, p, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
|
group.engine.router.Handle(method, p, func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
|
||||||
group.createContext(w, req, params, handlers).Next()
|
group.createContext(&ResponseWriter{w, -1}, req, params, handlers).Next()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -329,10 +329,10 @@ func (c *Context) JSON(code int, obj interface{}) {
|
|||||||
if code >= 0 {
|
if code >= 0 {
|
||||||
c.Writer.WriteHeader(code)
|
c.Writer.WriteHeader(code)
|
||||||
}
|
}
|
||||||
encoder := json.NewEncoder(c.Writer)
|
encoder := json.NewEncoder(&c.Writer)
|
||||||
if err := encoder.Encode(obj); err != nil {
|
if err := encoder.Encode(obj); err != nil {
|
||||||
c.Error(err, obj)
|
c.Error(err, obj)
|
||||||
http.Error(c.Writer, err.Error(), 500)
|
http.Error(&c.Writer, err.Error(), 500)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -343,10 +343,10 @@ func (c *Context) XML(code int, obj interface{}) {
|
|||||||
if code >= 0 {
|
if code >= 0 {
|
||||||
c.Writer.WriteHeader(code)
|
c.Writer.WriteHeader(code)
|
||||||
}
|
}
|
||||||
encoder := xml.NewEncoder(c.Writer)
|
encoder := xml.NewEncoder(&c.Writer)
|
||||||
if err := encoder.Encode(obj); err != nil {
|
if err := encoder.Encode(obj); err != nil {
|
||||||
c.Error(err, obj)
|
c.Error(err, obj)
|
||||||
http.Error(c.Writer, err.Error(), 500)
|
http.Error(&c.Writer, err.Error(), 500)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -358,12 +358,12 @@ func (c *Context) HTML(code int, name string, data interface{}) {
|
|||||||
if code >= 0 {
|
if code >= 0 {
|
||||||
c.Writer.WriteHeader(code)
|
c.Writer.WriteHeader(code)
|
||||||
}
|
}
|
||||||
if err := c.engine.HTMLTemplates.ExecuteTemplate(c.Writer, name, data); err != nil {
|
if err := c.engine.HTMLTemplates.ExecuteTemplate(&c.Writer, name, data); err != nil {
|
||||||
c.Error(err, map[string]interface{}{
|
c.Error(err, map[string]interface{}{
|
||||||
"name": name,
|
"name": name,
|
||||||
"data": data,
|
"data": data,
|
||||||
})
|
})
|
||||||
http.Error(c.Writer, err.Error(), 500)
|
http.Error(&c.Writer, err.Error(), 500)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
48
response_writer.go
Normal file
48
response_writer.go
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
package gin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
StatusUnset int = -1
|
||||||
|
)
|
||||||
|
|
||||||
|
type ResponseWriter struct {
|
||||||
|
http.ResponseWriter
|
||||||
|
status int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *ResponseWriter) WriteHeader(code int) {
|
||||||
|
w.status = code
|
||||||
|
w.ResponseWriter.WriteHeader(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *ResponseWriter) Write(data []byte) (int, error) {
|
||||||
|
// net/http.Response.Write only has two options: 200 or 500
|
||||||
|
// we will follow that lead and defer to their logic
|
||||||
|
|
||||||
|
// check if the write gave an error and set status accordingly
|
||||||
|
size, err := w.ResponseWriter.Write(data)
|
||||||
|
if err != nil {
|
||||||
|
// error on write, we give a 500
|
||||||
|
w.status = http.StatusInternalServerError
|
||||||
|
} else if w.WasWritten() == false {
|
||||||
|
// everything went okay and we never set a custom
|
||||||
|
// status so 200 it is
|
||||||
|
w.status = http.StatusOK
|
||||||
|
}
|
||||||
|
|
||||||
|
// can easily tap into Content-Length here with 'size'
|
||||||
|
return size, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// returns the status of the given response
|
||||||
|
func (w *ResponseWriter) Status() int {
|
||||||
|
return w.status
|
||||||
|
}
|
||||||
|
|
||||||
|
// return a boolean acknowledging if a status code has all ready been set
|
||||||
|
func (w *ResponseWriter) WasWritten() bool {
|
||||||
|
return w.status == StatusUnset
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user