Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions consts.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const (
LogTarget_Default = "dotweb_default"
LogTarget_HttpRequest = "dotweb_request"
LogTarget_HttpServer = "dotweb_server"
LogTarget_RequestTimeout = "dotweb_req_timeout"

LogLevel_Debug = "debug"
LogLevel_Info = "info"
Expand Down
17 changes: 17 additions & 0 deletions dotweb.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ type (
cache cache.Cache
OfflineServer servers.Server
Config *config.Config
Mock Mock
Middlewares []Middleware
ExceptionHandler ExceptionHandle
NotFoundHandler StandardHandle // NotFoundHandler 支持自定义404处理代码能力
Expand Down Expand Up @@ -214,6 +215,11 @@ func (app *DotWeb) UseTimeoutHook(handler StandardHandle, timeout time.Duration)
})
}

// SetMock set mock logic
func (app *DotWeb) SetMock(mock Mock){
app.Mock = mock
}

// SetExceptionHandle set custom error handler
func (app *DotWeb) SetExceptionHandle(handler ExceptionHandle) {
app.ExceptionHandler = handler
Expand Down Expand Up @@ -310,6 +316,11 @@ func (app *DotWeb) ListenAndServe(addr string) error {
app.IncludeDotwebGroup()
}

//special, if run mode is not develop, auto stop mock
if app.RunMode() != RunMode_Development{
app.Mock = nil
}

if app.HttpServer.ServerConfig().EnabledTLS {
err := app.HttpServer.ListenAndServeTLS(addr, app.HttpServer.ServerConfig().TLSCertFile, app.HttpServer.ServerConfig().TLSKeyFile)
return err
Expand Down Expand Up @@ -576,6 +587,12 @@ func (app *DotWeb) DefaultMethodNotAllowedHandler(ctx Context) {
ctx.WriteStringC(http.StatusMethodNotAllowed, http.StatusText(http.StatusMethodNotAllowed))
}

func DefaultTimeoutHookHandler(ctx Context){
realDration := ctx.Items().GetTimeDuration(ItemKeyHandleDuration)
logs := fmt.Sprintf("req %v, cost %v", ctx.Request().Url(), realDration.Seconds())
logger.Logger().Warn(logs, LogTarget_RequestTimeout)
}

// Close immediately stops the server.
// It internally calls `http.Server#Close()`.
func (app *DotWeb) Close() error {
Expand Down
69 changes: 0 additions & 69 deletions example/cache/main.go

This file was deleted.

4 changes: 4 additions & 0 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ func main() {
ctx.WriteJsonC(http.StatusInternalServerError, err.Error())
})

//设置超时钩子事件,当请求超过指定时间阀值,会自动调用传入的函数
//不会终止请求,只作为旁路执行
app.UseTimeoutHook(dotweb.DefaultTimeoutHookHandler, time.Second * 2)

//设置HttpModule
//InitModule(app)

Expand Down
50 changes: 50 additions & 0 deletions example/mock/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package main

import (
"fmt"
"github.com/devfeel/dotweb"
"strconv"
)

func main() {
//初始化DotServer
app := dotweb.New()

//设置dotserver日志目录
//如果不设置,默认不启用,且默认为当前目录
app.SetEnabledLog(true)

//开启development模式
app.SetDevelopmentMode()

//设置Mock逻辑
app.SetMock(AppMock())

//设置路由
InitRoute(app.HttpServer)

// 开始服务
port := 8080
fmt.Println("dotweb.StartServer => " + strconv.Itoa(port))
err := app.StartServer(port)
fmt.Println("dotweb.StartServer error => ", err)
}

// Index index handler
func Index(ctx dotweb.Context) error {
ctx.Response().Header().Set("Content-Type", "text/html; charset=utf-8")
err := ctx.WriteString("index => ", ctx.Request().Url())
return err
}

// InitRoute init app's route
func InitRoute(server *dotweb.HttpServer) {
server.Router().GET("/", Index)
}

// AppMock create app Mock
func AppMock() dotweb.Mock{
m := dotweb.NewStandardMock()
m.RegisterString("/", "mock data")
return m
}
61 changes: 61 additions & 0 deletions mock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package dotweb

const(
requestHeaderUseMockKey = "dotweb_req_mock"
requestHeaderUseMockFlag = "true"
)

// MockHandle the handle define on mock module
type MockHandle func(ctx Context)

// Mock the define Mock module
type Mock interface{
// Register register MockHandle on route
Register(route string, handler MockHandle)
// RegisterString register return mock string on route
RegisterString(route string, resData string)
// CheckNeedMock check is need do mock logic
CheckNeedMock(Context) bool
// Do do mock logic
Do(Context)
}

// StandardMock standard mock implement for Mock interface
type StandardMock struct{
routeMap map[string]MockHandle
}

// NewStandardMock create new StandardMock
func NewStandardMock() *StandardMock{
return &StandardMock{routeMap:make(map[string]MockHandle)}
}

// CheckNeedMock check is need do mock logic
func (m *StandardMock) CheckNeedMock(ctx Context) bool{
if ctx.Request().QueryHeader(requestHeaderUseMockKey) == requestHeaderUseMockFlag{
return true
}
return false
}

// Do do mock logic
func (m *StandardMock) Do(ctx Context){
handler, exists:=m.routeMap[ctx.RouterNode().Node().fullPath]
if exists{
handler(ctx)
}
}

// Register register MockHandle on route
func (m *StandardMock) Register(route string, handler MockHandle){
m.routeMap[route] = handler
}

// RegisterString register return mock string on route
func (m *StandardMock) RegisterString(route string, resData string){
m.routeMap[route] = func(ctx Context) {
ctx.WriteString(resData)
ctx.Response().SetHeader(requestHeaderUseMockKey, requestHeaderUseMockFlag)
ctx.End()
}
}
9 changes: 9 additions & 0 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,15 @@ func (r *router) wrapRouterHandle(handler HttpHandle, isHijack bool) RouterHandl
}
}()


//do mock, special, mock will ignore all middlewares
if r.server.DotApp.Mock != nil && r.server.DotApp.Mock.CheckNeedMock(httpCtx){
r.server.DotApp.Mock.Do(httpCtx)
if httpCtx.isEnd{
return
}
}

//处理用户handle
var ctxErr error
//if len(r.server.DotApp.Middlewares) > 0 {
Expand Down
27 changes: 27 additions & 0 deletions version.MD
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
## dotweb版本记录:


#### Version 1.5.7
* New Feature: Add integration Timeout Middleware, support DotWeb.UseTimeoutHook to use it
* Detail:
- Provide DefaultTimeoutHookHandler to simplify use, it will auto write log the req info which time out
- Example:
``` golang
app.UseTimeoutHook(dotweb.DefaultTimeoutHookHandler, time.Second * 2)
```
* New Feature: Add Mock module, support DotWeb.SetMock to use it
* Detail:
- Provide StandardMock to simplify use, it implement Mock interface
- also you can create custom implement
- you can register MockHandle or register return string
- register key only support route
- special: mock mode only effective in DevelopMode
- Example:
``` golang
func AppMock() dotweb.Mock{
m := dotweb.NewStandardMock()
m.RegisterString("/", "mock data")
return m
}
app.SetMock(AppMock())
```
* 2018-08-22 10:00

#### Version 1.5.6.1
* BugFixed: hystrix add doCleanHistoryCounter, used to clean history counter
* 2018-08-18 10:00
Expand Down