mirror of
https://gitee.com/johng/gf
synced 2026-06-06 02:25:47 +08:00
add more examples of middleware feature for ghttp.Server; release updates
This commit is contained in:
@ -35,9 +35,6 @@ func main() {
|
||||
g.ALL("/dashboard", func(r *ghttp.Request) {
|
||||
r.Response.Write("dashboard")
|
||||
})
|
||||
g.ALL("/user", func(r *ghttp.Request) {
|
||||
r.Response.Write("user")
|
||||
})
|
||||
})
|
||||
s.SetPort(8199)
|
||||
s.Run()
|
||||
|
||||
42
.example/net/ghttp/server/middleware/error_handling.go
Normal file
42
.example/net/ghttp/server/middleware/error_handling.go
Normal file
@ -0,0 +1,42 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gogf/gf/frame/g"
|
||||
"github.com/gogf/gf/net/ghttp"
|
||||
)
|
||||
|
||||
func MiddlewareAuth(r *ghttp.Request) {
|
||||
token := r.Get("token")
|
||||
if token == "123456" {
|
||||
r.Middleware.Next()
|
||||
} else {
|
||||
r.Response.WriteStatus(http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
|
||||
func MiddlewareCORS(r *ghttp.Request) {
|
||||
r.Response.CORSDefault()
|
||||
r.Middleware.Next()
|
||||
}
|
||||
|
||||
func MiddlewareError(r *ghttp.Request) {
|
||||
r.Middleware.Next()
|
||||
if r.Response.Status >= http.StatusInternalServerError {
|
||||
r.Response.ClearBuffer()
|
||||
r.Response.Write("Internal error occurred, please try again later.")
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
s := g.Server()
|
||||
s.Group("/api.v2", func(g *ghttp.RouterGroup) {
|
||||
g.Middleware(MiddlewareAuth, MiddlewareCORS, MiddlewareError)
|
||||
g.ALL("/user/list", func(r *ghttp.Request) {
|
||||
panic("db error: sql is xxxxxxx")
|
||||
})
|
||||
})
|
||||
s.SetPort(8199)
|
||||
s.Run()
|
||||
}
|
||||
@ -28,6 +28,7 @@
|
||||
## 功能改进
|
||||
|
||||
1. `ghttp`
|
||||
- 改进`Request`参数解析方式:https://goframe.org/net/ghttp/request
|
||||
- `Cookie`及`Session`的`TTL`配置数据类型修改为`time.Duration`;
|
||||
- 新增允许同时通过`Header/Cookie`传递`SessionId`;
|
||||
- 新增`ConfigFromMap/SetConfigWithMap`方法,支持通过`map`参数设置WebServer;
|
||||
|
||||
Reference in New Issue
Block a user