packet main
负责调用main()
只负责启动和关闭server
用到的是:
packet app
是真正的服务器应用包
使用了4个packet:
"github.com/devfeel/dotweb"
"github.com/track/blogserver/pkg/config"
"github.com/track/blogserver/pkg/controllers"
"github.com/track/blogserver/pkg/routers"
packet dotweb
是一个webserver框架
https://www.kancloud.cn/devfeel/dotweb/346608
主要提供:
1 ServerFile访问服务器静态文件
2 模板渲染 可以指定模板并且自定义数据
3 路由,可以实现url和handler的匹配,比如:app.HttpServer.GET("/hello", hello)
也可以用GetRouterName获取参数的值
app := dotweb.New()
app.HttpServer.GET("/hello/:name", func(ctx dotweb.Context) error{
return ctx.WriteString("hello " + ctx.GetRouterName("name"))
})
也可以通过Group来定义组路由
import "github.com/devfeel/middleware/accesslog"
g := app.HttpServer.Group("/admin")
g.Use(accesslog.Middleware())
g.Get("/index", func(ctx dotweb.Context) error {
ctx.WriteString("/admin/index")
return nil
}
4 Cookie
5 Session
6 http请求
可以通过 FormValue 获取 表单数据
可以通过 QueryString 获取 Get参数
可以通过 PostFormValue 获取 PostForm
可以通过 PostBody 获取 Post Body
可以通过 Bind 绑定一个请求内容体到 go 的结构体
// User
type UserInfo struct {
UserName string
Sex int
}
// Handler
func(ctx dotweb.Context) (err error) {
user := new(User)
if err := ctx.Bind(user); err != nil {
return err
}
ctx.WriteString(fmt.Sprint(user))
return nil
}
7 HTTP响应
https://www.kancloud.cn/devfeel/dotweb/347467
可以通过 WriteString 发送一个默认200状态码的纯文本响应。
可以通过 WriteStringC 发送一个带有状态码的纯文本响应。
可以通过 WriteJson 用于发送一个默认200状态码的 json 对象。它会将 golang 的对象转换成 json 字符串。
可以通过 WriteJsonC 用于发送一个带有状态码的 json 对象。它会将 golang 的对象转换成 json 字符串。
可以通过 WriteJsonp 用于将golang对象转换成 json 并通过回调以 jsonp 的结构发送。
可以通过 View 发送一个默认200状态码的动态生成 html 内容。
可以通过 ViewC 发送一个带有状态码的动态生成 html 内容。
可以通过 Redirect 提供一个 url 用于重定向。
8 错误处理 & 404 设置
最常用的方法:
SetExceptionHandle 设置自定义异常处理接口
当发生404异常时,会默认使用http.NotFound处理,通过DotWeb.SetNotFoundHandle(handler NotFoundHandle)实现自定义处理逻辑
eg:
//配置自定义error
func (app *App) initError() {
ec := controllers.NewErrorController()
app.Server.SetNotFoundHandle(ec.NotFound)
app.Server.SetExceptionHandle(ec.Internal)
app.Server.SetMethodNotAllowedHandle(ec.MethodNotAllowed)
}
error controller的实现:
package controllers
import (
"fmt"
"github.com/devfeel/dotweb"
"github.com/track/blogserver/pkg/common"
"