Skip to content

Commit

Permalink
Merge pull request devfeel#163 from devfeel/develop
Browse files Browse the repository at this point in the history
Version 1.5.9 - Add HttpServer.SetEnabledStaticFileMiddleware & Group.ServerFile & Ping Check
  • Loading branch information
devfeel authored Oct 30, 2018
2 parents dbff535 + 654ebc6 commit 0214093
Show file tree
Hide file tree
Showing 7 changed files with 71 additions and 14 deletions.
1 change: 1 addition & 0 deletions config/configs.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ type (
EnabledAutoCORS bool `xml:"enabledautocors,attr"` //设置是否自动跨域支持,若设置,默认“GET, POST, PUT, DELETE, OPTIONS”全部请求均支持跨域
EnabledIgnoreFavicon bool `xml:"enabledignorefavicon,attr"` //设置是否忽略favicon.ico请求,若设置,网站将把所有favicon.ico请求直接空返回
EnabledBindUseJsonTag bool `xml:"enabledbindusejsontag,attr"` //设置bind是否启用json标签,默认不启用,若设置,bind自动识别json tag,忽略form tag
EnabledStaticFileMiddleware bool //The flag which enabled or disabled middleware for static-file route
Port int `xml:"port,attr"` //端口
EnabledTLS bool `xml:"enabledtls,attr"` //是否启用TLS模式
TLSCertFile string `xml:"tlscertfile,attr"` //TLS模式下Certificate证书文件地址
Expand Down
6 changes: 1 addition & 5 deletions dotweb.go
Original file line number Diff line number Diff line change
Expand Up @@ -473,13 +473,9 @@ func (app *DotWeb) initBindMiddleware() {
xg := g.(*xGroup)
if len(xg.middlewares) <= 0 {
continue
} else {
firstMiddleware := &xMiddleware{}
firstMiddleware.SetNext(xg.middlewares[0])
xg.middlewares = append([]Middleware{firstMiddleware}, xg.middlewares...)
}
for fullExpress, _ := range xg.allRouterExpress {
expresses := strings.Split(fullExpress, "_")
expresses := strings.Split(fullExpress, routerExpressSplit)
if len(expresses) < 2 {
continue
}
Expand Down
13 changes: 12 additions & 1 deletion group.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ type (
PATCH(path string, h HttpHandle) RouterNode
POST(path string, h HttpHandle) RouterNode
PUT(path string, h HttpHandle) RouterNode
ServerFile(path string, fileroot string) RouterNode
RegisterRoute(method, path string, h HttpHandle) RouterNode
}
xGroup struct {
Expand Down Expand Up @@ -85,6 +86,14 @@ func (g *xGroup) PUT(path string, h HttpHandle) RouterNode {
return g.add(RouteMethod_PUT, path, h)
}

// PUT implements `Router#PUT()` for sub-routes within the Group.
func (g *xGroup) ServerFile(path string, fileroot string) RouterNode {
g.allRouterExpress[RouteMethod_GET+routerExpressSplit+g.prefix+path] = struct{}{}
node := g.server.Router().ServerFile(g.prefix+path, fileroot)
node.Node().groupMiddlewares = g.middlewares
return node
}

// Group creates a new sub-group with prefix and optional sub-group-level middleware.
func (g *xGroup) Group(prefix string, m ...Middleware) Group {
return NewGroup(g.prefix+prefix, g.server).Use(g.middlewares...).Use(m...)
Expand All @@ -96,7 +105,9 @@ func (g *xGroup) RegisterRoute(method, path string, handler HttpHandle) RouterNo

func (g *xGroup) add(method, path string, handler HttpHandle) RouterNode {
node := g.server.Router().RegisterRoute(method, g.prefix+path, handler)
g.allRouterExpress[method+"_"+g.prefix+path] = struct{}{}
g.allRouterExpress[method+routerExpressSplit+g.prefix+path] = struct{}{}
node.Node().groupMiddlewares = g.middlewares
return node
}


9 changes: 7 additions & 2 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type Request struct {
*http.Request
httpCtx *HttpContext
postBody []byte
realUrl string
isReadBody bool
requestID string
}
Expand Down Expand Up @@ -175,5 +176,9 @@ func (req *Request) IsAJAX() bool {

// Url get request url
func (req *Request) Url() string {
return req.URL.String()
}
if req.realUrl != ""{
return req.realUrl
}else{
return req.URL.String()
}
}
35 changes: 29 additions & 6 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -359,12 +359,25 @@ func (r *router) wrapRouterHandle(handler HttpHandle, isHijack bool) RouterHandl
//wrap fileHandler to httprouter.Handle
func (r *router) wrapFileHandle(fileHandler http.Handler) RouterHandle {
return func(httpCtx *HttpContext) {
httpCtx.handler = transStaticFileHandler(fileHandler)
startTime := time.Now()
httpCtx.Request().realUrl = httpCtx.Request().URL.String()
httpCtx.Request().URL.Path = httpCtx.RouterParams().ByName("filepath")
fileHandler.ServeHTTP(httpCtx.Response().Writer(), httpCtx.Request().Request)
timetaken := int64(time.Now().Sub(startTime) / time.Millisecond)
//HttpServer Logging
logger.Logger().Debug(httpCtx.Request().Url()+" "+logRequest(httpCtx.Request().Request, timetaken), LogTarget_HttpRequest)
if httpCtx.HttpServer().ServerConfig().EnabledStaticFileMiddleware && len(httpCtx.routerNode.AppMiddlewares()) > 0 {
ctxErr := httpCtx.routerNode.AppMiddlewares()[0].Handle(httpCtx)
if ctxErr != nil {
if r.server.DotApp.ExceptionHandler != nil {
r.server.DotApp.ExceptionHandler(httpCtx, ctxErr)
core.GlobalState.AddErrorCount(httpCtx.Request().Path(), ctxErr, 1)
}
}
} else {
httpCtx.Handler()(httpCtx)
}
if logger.EnabledLog {
timetaken := int64(time.Now().Sub(startTime) / time.Millisecond)
logger.Logger().Debug(httpCtx.Request().Url() +" "+logRequest(httpCtx.Request().Request, timetaken), LogTarget_HttpRequest)
}
}
}

Expand Down Expand Up @@ -447,7 +460,8 @@ func (r *router) RegisterRoute(routeMethod string, path string, handle HttpHandl
r.add(RouteMethod_OPTIONS, realPath, r.wrapRouterHandle(handle, false))
} else {
//Single GET\POST\DELETE\PUT\HEAD\PATCH\OPTIONS mode
node = r.add(routeMethod, realPath, r.wrapRouterHandle(handle, false))
r.add(routeMethod, realPath, r.wrapRouterHandle(handle, false))
node = r.getNode(routeMethod, realPath)
}
}
logger.Logger().Debug("DotWeb:Router:RegisterRoute success ["+routeMethod+"] ["+realPath+"] ["+handleName+"]", LogTarget_HttpServer)
Expand Down Expand Up @@ -487,6 +501,7 @@ func (r *router) RegisterRoute(routeMethod string, path string, handle HttpHandl
// simple demo:server.ServerFile("/src/*filepath", "/var/www")
func (r *router) ServerFile(path string, fileroot string) RouterNode {
realPath := r.server.VirtualPath() + path
routeMethod := RouteMethod_GET
node := &Node{}
if len(realPath) < 10 || realPath[len(realPath)-10:] != "/*filepath" {
panic("path must end with /*filepath in path '" + realPath + "'")
Expand All @@ -497,7 +512,8 @@ func (r *router) ServerFile(path string, fileroot string) RouterNode {
root = &core.HideReaddirFS{root}
}
fileServer := http.FileServer(root)
node = r.add(RouteMethod_GET, realPath, r.wrapFileHandle(fileServer))
r.add(routeMethod, realPath, r.wrapFileHandle(fileServer))
node = r.getNode(routeMethod, realPath)
return node
}

Expand Down Expand Up @@ -624,6 +640,13 @@ func (r *router) wrapWebSocketHandle(handler HttpHandle) websocket.Handler {
}
}

func transStaticFileHandler(fileHandler http.Handler) HttpHandle{
return func(httpCtx Context) error {
fileHandler.ServeHTTP(httpCtx.Response().Writer(), httpCtx.Request().Request)
return nil
}
}

// existsRouter check is exists with method and path in current router
func (r *router) existsRouter(method, path string) bool {
_, exists := r.allRouterExpress[method + routerExpressSplit + path]
Expand Down
6 changes: 6 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,12 @@ func (server *HttpServer) SetEnabledDetailRequestData(isEnabled bool) {
logger.Logger().Debug("DotWeb:HttpServer SetEnabledDetailRequestData ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer)
}

// SetEnabledStaticFileMiddleware set flag which enabled or disabled middleware for static-file route
func (server *HttpServer) SetEnabledStaticFileMiddleware(isEnabled bool){
server.ServerConfig().EnabledStaticFileMiddleware = isEnabled
logger.Logger().Debug("DotWeb:HttpServer SetEnabledStaticFileMiddleware ["+strconv.FormatBool(isEnabled)+"]", LogTarget_HttpServer)
}

// RegisterModule 添加处理模块
func (server *HttpServer) RegisterModule(module *HttpModule) {
server.Modules = append(server.Modules, module)
Expand Down
15 changes: 15 additions & 0 deletions version.MD
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
## dotweb版本记录:

#### Version 1.5.9
* New Feature: Add HttpServer.SetEnabledStaticFileMiddleware, used to set flag which enabled or disabled middleware for static-file route
* Detail:
- if enabled, when visit static file route, will use middlewares like other router
- the execute order: App -> Group -> Router
- default is not enabled
* Example:
``` golang
app.HttpServer.SetEnabledStaticFileMiddleware(true)
```
* New Feature: Add Group.ServerFile used to registe static file router in group
* New Feature: Add ping check when init redis session, if can not ping successful, it will panic error info, like "panic: redis session [redis] ping error"
* update dotweb-example/static
* 2018-10-30 15:00

#### Version 1.5.8
* New Feature: Add HttpServer.SetBinder, used to set custom Binder on HttpServer
* Detail:
Expand Down

0 comments on commit 0214093

Please sign in to comment.