Go開源: DotWeb - 簡約大方的 Go Web 微型框架
DotWeb
簡約大方的go Web微型框架
安裝:
go get -u github.com/devfeel/dotweb
快速開始:
func StartServer() error {
//初始化DotServer
dotserver := dotweb.New()
//設置dotserver日志目錄
dotserver.SetLogPath("/home/logs/wwwroot/")
//設置路由
dotserver.HttpServer.GET("/index", func(ctx *dotweb.HttpContext) {
ctx.WriteString("welcome to my first web!")
})
//開始服務
err := dotserver.StartServer(80)
return err
}
特性
- 支持靜態路由、參數路由
- 路由支持文件/目錄服務
- 中間件支持
- 支持JSON/JSONP/HTML格式輸出
- 統一的HTTP錯誤處理
- 統一的日志處理
- 支持Hijack與websocket
路由
常規路由
目前支持GET\POST\HEAD\OPTIONS\PUT\PATCH\DELETE 這幾類請求方法 另外也支持HiJack\WebSocket\ServerFile三類特殊應用
1、HttpServer.GET(path string, handle HttpHandle)
2、HttpServer.POST(path string, handle HttpHandle)
3、HttpServer.HEAD(path string, handle HttpHandle)
4、HttpServer.OPTIONS(path string, handle HttpHandle)
5、HttpServer.PUT(path string, handle HttpHandle)
6、HttpServer.PATCH(path string, handle HttpHandle)
7、HttpServer.DELETE(path string, handle HttpHandle)
8、HttpServer.HiJack(path string, handle HttpHandle)
9、HttpServer.WebSocket(path string, handle HttpHandle)
10、HttpServer.RegisterRoute(routeMethod string, path string, handle HttpHandle)
接受兩個參數,一個是URI路徑,另一個是 HttpHandle 類型,設定匹配到該路徑時執行的方法;
靜態路由
靜態路由語法就是沒有任何參數變量,pattern是一個固定的字符串。
package main
import (
"github.com/devfeel/dotweb"
)
func main() {
dotserver := dotweb.New()
dotserver.Get("/hello", func(ctx *dotweb.HttpContext) {
ctx.WriteString("hello world!")
})
dotserver.StartServer(80)
}</code></pre>
測試: curl http://127.0.0.1/hello
參數路由
參數路由以冒號 : 后面跟一個字符串作為參數名稱,可以通過 HttpContext的 GetRouterName 方法獲取路由參數的值。
package main
import (
"github.com/devfeel/dotweb"
)
func main() {
dotserver := dotweb.New()
dotserver.Get("/hello/:name", func(ctx dotweb.HttpContext) {
ctx.WriteString("hello " + ctx.GetRouterName("name"))
})
dotserver.Get("/news/:category/:newsid", func(ctx dotweb.HttpContext) {
category := ctx.GetRouterName("category")
newsid := ctx.GetRouterName("newsid")
ctx.WriteString("news info: category=" + category + " newsid=" + newsid)
})
dotserver.StartServer(80)
}</code></pre>
測試:
curl http://127.0.0.1/hello/devfeel
curl http://127.0.0.1/hello/category1/1
中間件(攔截器)
RegisterModule
- 支持OnBeginRequest、OnEndRequest兩類中間件
- 通過實現HttpModule.OnBeginRequest、HttpModule.OnEndRequest接口實現自定義中間件
- 通過設置HttpContext.End()提前終止請求
異常
500錯誤
- 默認設置: 當發生未處理異常時,會根據DebugMode向頁面輸出默認錯誤信息或者具體異常信息,并返回 500 錯誤頭
- 自定義: 通過DotServer.SetExceptionHandle(handler *ExceptionHandle)實現自定義異常處理邏輯
type ExceptionHandle func(*HttpContext, interface{})
外部依賴
httprouter - github.com/julienschmidt/httprouter
websocket - golang.org/x/net/websocket
相關項目
項目簡介:token服務,提供token一致性服務以及相關的全局ID生成服務等