安装:
$ go get -u github.com/devfeel/dotweb
注意:确保 GOPATH GOROOT 已经配置
导入:
import "github.com/devfeel/dotweb"
- HTTP 服务器
func main() {
app := dotweb.New()
err := app.StartServer(80)
if err !=nil{
fmt.Println("dotweb.StartServer error => ", err)
}
}
- 生命周期
- Context
- 基本路由
dotweb 框架中路由是基于httprouter演变而来。
//初始化DotServer
app := dotweb.New()
//设置dotserver日志目录
app.SetLogPath(file.GetCurrentDirectory())
//设置路由
app.HttpServer.GET("/", Index)
app.HttpServer.GET("/d/:x/y", Index)
app.HttpServer.GET("/any", Any)
- 路由参数
API 参数以冒号 : 后面跟一个字符串作为参数名称,可以通过 GetRouterName 方法获取路由参数的值。
app.HttpServer.GET("/hello/:name", func(ctx dotweb.Context) error {
return ctx.WriteString("hello " + ctx.GetRouterName("name"))
})
URL 参数通过 QueryString、QueryInt 或 QueryInt64 方法获取
// url 为 http://localhost:8080/hello?name=billy时
// 输出 hello 123
app.HttpServer.GET("/hello", func(ctx dotweb.Context) error {
return ctx.WriteString("hello " + ctx.QueryString("name"))
})
表单参数通过 PostFormValue 方法获取
app.HttpServer.POST("/user", func(ctx dotweb.Context) error {
name := ctx.PostFormValue("name")
age := ctx.PostFormValue("age")
return ctx.WriteString("name is " + name + ", age is " + age)
})
- 路由群组
//设置路由组
userCenterGroup := app.HttpServer.Group("/usercenter")
userCenterGroup.GET("/userinfo", getUserInfo)
userCenterGroup.GET("/account",getUserAccount)
- 数据解析绑定
模型绑定可以将请求体绑定给一个类型,目前支持绑定的类型有 JSON, XML 和标准表单数据 (foo=bar&boo=baz)。
要注意的是绑定时需要给字段设置绑定类型的标签。比如绑定 JSON 数据时,设置 json:"fieldname"
。
使用绑定方法时,dotweb 会根据请求头中 Content-Type 来自动判断需要解析的类型。如果你明确绑定的类型。
// Binding from JSON
type User struct {
Name string `form:"name"`
Age int `form:"age"`
}
func main() {
app := dotweb.New()
// 绑定普通表单或json格式
app.HttpServer.POST("/user", func(ctx dotweb.Context) error {
user := new(User)
if err := ctx.Bind(user); err != nil {
return ctx.WriteString("Bind err:" + err.Error())
}
return ctx.WriteString("Bind:" + fmt.Sprint(user))
})
// 只绑定JSON的例子 ({"user": "manu", "age": 12})
app.HttpServer.POST("/userjson", func(ctx dotweb.Context) error {
user := new(User)
if err := ctx.BindJsonBody(user); err != nil {
return ctx.WriteString("Bind err:" + err.Error())
}
return ctx.WriteString("Bind:" + fmt.Sprint(user))
})
app.StartServer(8888)
}
- 请求头
- 请求参数
- Cookies
- 上传文件
- 响应头
- 附加Cookie
- 字符串响应
ctx.WriteString("")
ctx.WriteStringC(http.StatusOK, "")
- JSON/Byte/Html响应
ctx.WriteBlob([]byte)
ctx.WriteBlobC(http.StatusOK,[]byte)
ctx.WriteHtml(html)
ctx.WriteHtmlC(http.StatusOK,html)
ctx.WriteJson(user)
ctx.WriteJsonC(http.StatusOK, user)
ctx.WriteJsonBlob([]byte)
ctx.WriteJsonBlobC(http.StatusOK, []byte)
- 视图响应
使用 View() 方法来加载模板文件,默认当前程序根目录模板路径
func main() {
app := dotweb.New()
//set default template path, support multi path
//模板查找顺序从最后一个插入的元素开始往前找
app.HttpServer.GET("/", TestView)
//设置模板路径
app.HttpServer.Renderer().SetTemplatePath("views/")
app.HttpServer.GET("/", func(ctx dotweb.Context) error {
ctx.ViewData().Set("data", "测试信息")
//加载模板
err := ctx.View("testview.html")
return err
})
app.StartServer(8888)
}
模板结构定义
<html>
<h1>
{{ .data }}
</h1>
</html>
不同文件夹下模板名字可以相同,此时需要 View() 指定模板路径
ctx.View("/test/testview.html")
app.HttpServer.GET("/", func(ctx dotweb.Context) error {
ctx.ViewData().Set("data", "图书信息")
type BookInfo struct {
Name string
Size int64
}
m := make([]*BookInfo, 5)
m[0] = &BookInfo{Name: "book0", Size: 1}
m[1] = &BookInfo{Name: "book1", Size: 10}
m[2] = &BookInfo{Name: "book2", Size: 100}
m[3] = &BookInfo{Name: "book3", Size: 1000}
m[4] = &BookInfo{Name: "book4", Size: 10000}
ctx.ViewData().Set("Books", m)
//加载test文件夹下testview模板
err := ctx.View("/test/testview.html")
//加载test1文件夹下testview模板
err := ctx.View("test1/testview.html")
return err
})
views/test/testview.html
<html>
<h1>{{.data}}</h1>
<br>
<b>Books:</b>
<br>
{{range .Books}}
BookName => {{.Name}}; Size => {{.Size}}
</html>
- 文件响应
//相对路径
app.HttpServer.ServerFile("/src/*filepath", "./var/www")
//等价
app.HttpServer.ServerFile("/src/*filepath", "var/www")
- 重定向
app.HttpServer.GET("/redirect", func(ctx dotweb.Context) error {
//内部重定向
ctx.Redirect(http.StatusMovedPermanently, "src/1.html")
//外部的重定向
ctx.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
return nil
})
- 同步异步
goroutine 机制可以方便地实现异步处理
- 传参
- 视图组件
-
分类使用方式
支持粒度:App、Group、RouterNode
启用顺序:App -> Group -> RouterNode,同级别下按Use的引入顺序执行
// 1.全局中间件
app.Use(cors.DefaultMiddleware())
// 2.单路由的中间件,可以Use多个
app.HttpServer.POST("/",user).Use(...).Use(...)
// 3.群组路由的中间件
userCenterGroup := app.HttpServer.Group("/usercenter").Use(...)
// 或者这样用:
userCenterGroup.Use(...).Use(...)
- 自定义中间件
//定义
func Handle(ctx dotweb.Context) error {
//处理前
m.Next(ctx)
//处理后
return nil
}
更多自定义中间件参考: https://github.com/devfeel/middleware
-
中间件参数
-
内置中间件
app.UseRequestLog()//简单请求日志中间件
app.UseTimeoutHook()//超时处理中间件
参考 https://github.com/devfeel/database
- Mongodb
- Mysql
- SqlServer