add more examples of middleware feature for ghttp.Server; release updates

This commit is contained in:
John
2019-09-19 21:17:54 +08:00
parent 1181ab499c
commit ec994f3080
3 changed files with 43 additions and 3 deletions

View File

@ -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()

View 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()
}

View File

@ -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