Try to refine the panic things.

This commit is contained in:
zicla
2018-11-30 17:37:52 +08:00
parent 6485e3b48e
commit b55a993b35
10 changed files with 84 additions and 90 deletions

View File

@ -23,10 +23,9 @@ func main() {
http.Handle("/", rest.CONTEXT.Router) http.Handle("/", rest.CONTEXT.Router)
dotPort := fmt.Sprintf(":%v", rest.CONFIG.ServerPort)
rest.LOGGER.Info("App started at http://localhost:%v", rest.CONFIG.ServerPort) rest.LOGGER.Info("App started at http://localhost:%v", rest.CONFIG.ServerPort)
dotPort := fmt.Sprintf(":%v", rest.CONFIG.ServerPort)
err1 := http.ListenAndServe(dotPort, nil) err1 := http.ListenAndServe(dotPort, nil)
if err1 != nil { if err1 != nil {
log.Fatal("ListenAndServe: ", err1) log.Fatal("ListenAndServe: ", err1)

View File

@ -98,16 +98,20 @@ func (this *BaseController) Wrap(f func(writer http.ResponseWriter, request *htt
} }
} }
//返回成功的结果。 //返回成功的结果。支持放置三种类型 1.字符串 2. WebResult对象 3.空指针 4.任意类型
func (this *BaseController) Success(data interface{}) *WebResult { func (this *BaseController) Success(data interface{}) *WebResult {
var webResult *WebResult = nil var webResult *WebResult = nil
if value, ok := data.(string); ok { if value, ok := data.(string); ok {
//返回一句普通的消息
webResult = &WebResult{Code: CODE_WRAPPER_OK.Code, Msg: value} webResult = &WebResult{Code: CODE_WRAPPER_OK.Code, Msg: value}
} else if value, ok := data.(*WebResult); ok { } else if value, ok := data.(*WebResult); ok {
//返回一个webResult对象
webResult = value webResult = value
} else if _, ok := data.(types.Nil); ok { } else if _, ok := data.(types.Nil); ok {
//返回一个空指针
webResult = ConstWebResult(CODE_WRAPPER_OK) webResult = ConstWebResult(CODE_WRAPPER_OK)
} else { } else {
//返回的类型不明确。
webResult = &WebResult{Code: CODE_WRAPPER_OK.Code, Data: data} webResult = &WebResult{Code: CODE_WRAPPER_OK.Code, Data: data}
} }
return webResult return webResult
@ -130,49 +134,6 @@ func (this *BaseController) Error(err interface{}) *WebResult {
return webResult return webResult
} }
//能找到一个user就找到一个
func (this *BaseController) findUser(writer http.ResponseWriter, request *http.Request) *User {
//验证用户是否已经登录。
sessionCookie, err := request.Cookie(COOKIE_AUTH_KEY)
if err != nil {
this.logger.Warn("获取用户cookie信息失败啦~")
return nil
}
sessionId := sessionCookie.Value
this.logger.Info("findUser sessionId = %s", sessionId)
//去缓存中捞取看看
cacheItem, err := CONTEXT.SessionCache.Value(sessionId)
if err != nil {
this.logger.Warn("获取缓存时出错了" + err.Error())
return nil
}
if cacheItem.Data() == nil {
this.logger.Warn("cache item中已经不存在了 " + err.Error())
return nil
}
if value, ok := cacheItem.Data().(*User); ok {
return value
} else {
this.logger.Error("cache item中的类型不是*User ")
}
return nil
}
func (this *BaseController) checkUser(writer http.ResponseWriter, request *http.Request) *User {
if this.findUser(writer, request) == nil {
panic(ConstWebResult(CODE_WRAPPER_LOGIN))
} else {
return this.findUser(writer, request)
}
}
//允许跨域请求 //允许跨域请求
func (this *BaseController) allowCORS(writer http.ResponseWriter) { func (this *BaseController) allowCORS(writer http.ResponseWriter) {
writer.Header().Add("Access-Control-Allow-Origin", "*") writer.Header().Add("Access-Control-Allow-Origin", "*")

View File

@ -29,3 +29,45 @@ func (this *Bean) PanicError(err error) {
func (this *Bean) PanicWebError(msg string, httpStatusCode int) { func (this *Bean) PanicWebError(msg string, httpStatusCode int) {
panic(&WebError{Msg: msg, Code: httpStatusCode}) panic(&WebError{Msg: msg, Code: httpStatusCode})
} }
//能找到一个user就找到一个
func (this *Bean) findUser(writer http.ResponseWriter, request *http.Request) *User {
//验证用户是否已经登录。
sessionCookie, err := request.Cookie(COOKIE_AUTH_KEY)
if err != nil {
this.logger.Warn("cookie 信息不存在~")
return nil
}
sessionId := sessionCookie.Value
//去缓存中捞取看看
cacheItem, err := CONTEXT.SessionCache.Value(sessionId)
if err != nil {
this.logger.Warn("获取缓存时出错了" + err.Error())
return nil
}
if cacheItem == nil || cacheItem.Data() == nil {
this.logger.Warn("cache item中已经不存在了 ")
return nil
}
if value, ok := cacheItem.Data().(*User); ok {
return value
} else {
this.logger.Error("cache item中的类型不是*User ")
}
return nil
}
//获取当前登录的用户,找不到就返回登录错误
func (this *Bean) checkUser(writer http.ResponseWriter, request *http.Request) *User {
if this.findUser(writer, request) == nil {
panic(ConstWebResult(CODE_WRAPPER_LOGIN))
} else {
return this.findUser(writer, request)
}
}

View File

@ -150,7 +150,7 @@ func LoadConfigFromFile() {
filePath := GetConfPath() + "/tank.json" filePath := GetConfPath() + "/tank.json"
content, err := ioutil.ReadFile(filePath) content, err := ioutil.ReadFile(filePath)
if err != nil { if err != nil {
LOGGER.Warn(fmt.Sprintf("无法找到配置文件:%s,错误:%v\n将使用config.go中的默认配置项。", filePath, err)) LOGGER.Warn("无法找到配置文件:%s 将使用config.go中的默认配置项。", filePath)
} else { } else {
// 用 json.Unmarshal // 用 json.Unmarshal
err := json.Unmarshal(content, CONFIG) err := json.Unmarshal(content, CONFIG)
@ -170,7 +170,7 @@ func LoadConfigFromEnvironment() {
if e == nil { if e == nil {
CONFIG.ServerPort = i CONFIG.ServerPort = i
} else { } else {
LOGGER.Panic(fmt.Sprintf("环境变量TANK_SERVER_PORT必须为整数%v", tmpServerPort)) LOGGER.Panic("环境变量TANK_SERVER_PORT必须为整数%v", tmpServerPort)
} }
} }
@ -185,7 +185,7 @@ func LoadConfigFromEnvironment() {
if e == nil { if e == nil {
CONFIG.MysqlPort = i CONFIG.MysqlPort = i
} else { } else {
LOGGER.Panic(fmt.Sprintf("环境变量TANK_MYSQL_PORT必须为整数%v", tmpMysqlPort)) LOGGER.Panic("环境变量TANK_MYSQL_PORT必须为整数%v", tmpMysqlPort)
} }
} }

View File

@ -5,7 +5,6 @@ package rest
*/ */
type Footprint struct { type Footprint struct {
Base Base
SessionId string `json:"sessionId"`
UserUuid string `json:"userUuid"` UserUuid string `json:"userUuid"`
Ip string `json:"ip"` Ip string `json:"ip"`
Host string `json:"host"` Host string `json:"host"`

View File

@ -2,15 +2,15 @@ package rest
import ( import (
"encoding/json" "encoding/json"
"fmt"
"net/http" "net/http"
"time"
) )
//@Service //@Service
type FootprintService struct { type FootprintService struct {
Bean Bean
footprintDao *FootprintDao footprintDao *FootprintDao
userDao *UserDao userDao *UserDao
} }
//初始化方法 //初始化方法
@ -38,23 +38,8 @@ func (this *FootprintService) Detail(uuid string) *Footprint {
return footprint return footprint
} }
//记录访问记录 //记录访问记录
func (this *FootprintService) Trace(writer http.ResponseWriter, request *http.Request) { func (this *FootprintService) Trace(writer http.ResponseWriter, request *http.Request, duration time.Duration, success bool) {
//手动装填本实例的Bean. 这里必须要用中间变量方可。
var footprintDao *FootprintDao
b := CONTEXT.GetBean(footprintDao)
if b, ok := b.(*FootprintDao); ok {
footprintDao = b
}
fmt.Printf("Host = %s Uri = %s Path = %s RawPath = %s RawQuery = %s \n",
request.Host,
request.RequestURI,
request.URL.Path,
request.URL.RawPath,
request.URL.RawQuery)
params := make(map[string][]string) params := make(map[string][]string)
@ -76,18 +61,23 @@ func (this *FootprintService) Trace(writer http.ResponseWriter, request *http.Re
paramsString = string(paramsData) paramsString = string(paramsData)
} }
//将文件信息存入数据库中。 user := this.findUser(writer, request)
footprint := &Footprint{ userUuid := ""
SessionId: "", if user != nil {
UserUuid: "testUserUUid", userUuid = user.Uuid
Ip: GetIpAddress(request),
Host: request.Host,
Uri: request.URL.Path,
Params: paramsString,
Cost: 0,
Success: true,
} }
footprint = footprintDao.Create(footprint) //将文件信息存入数据库中。
footprint := &Footprint{
UserUuid: userUuid,
Ip: GetIpAddress(request),
Host: request.Host,
Uri: request.URL.Path,
Params: paramsString,
Cost: int64(duration / time.Millisecond),
Success: success,
}
footprint = this.footprintDao.Create(footprint)
} }

View File

@ -32,11 +32,11 @@ func (this *Logger) Debug(format string, v ...interface{}) {
} }
func (this *Logger) Info(format string, v ...interface{}) { func (this *Logger) Info(format string, v ...interface{}) {
this.log("[info]", format, v...) this.log("[info ]", format, v...)
} }
func (this *Logger) Warn(format string, v ...interface{}) { func (this *Logger) Warn(format string, v ...interface{}) {
this.log("[warn]", format, v...) this.log("[warn ]", format, v...)
} }
func (this *Logger) Error(format string, v ...interface{}) { func (this *Logger) Error(format string, v ...interface{}) {

View File

@ -7,6 +7,7 @@ import (
"net/http" "net/http"
"os" "os"
"strings" "strings"
"time"
) )
//用于处理所有前来的请求 //用于处理所有前来的请求
@ -46,7 +47,7 @@ func NewRouter() *Router {
} }
//全局的异常捕获 //全局的异常捕获
func (this *Router) GlobalPanicHandler(writer http.ResponseWriter, request *http.Request) { func (this *Router) GlobalPanicHandler(writer http.ResponseWriter, request *http.Request, startTime time.Time) {
if err := recover(); err != nil { if err := recover(); err != nil {
LOGGER.Error(fmt.Sprintf("全局异常: %v", err)) LOGGER.Error(fmt.Sprintf("全局异常: %v", err))
@ -85,6 +86,9 @@ func (this *Router) GlobalPanicHandler(writer http.ResponseWriter, request *http
var json = jsoniter.ConfigCompatibleWithStandardLibrary var json = jsoniter.ConfigCompatibleWithStandardLibrary
b, _ := json.Marshal(webResult) b, _ := json.Marshal(webResult)
//错误情况记录。
go this.footprintService.Trace(writer, request, time.Now().Sub(startTime), false)
_, err := fmt.Fprintf(writer, string(b)) _, err := fmt.Fprintf(writer, string(b))
if err != nil { if err != nil {
fmt.Printf("输出结果时出错了\n") fmt.Printf("输出结果时出错了\n")
@ -95,9 +99,11 @@ func (this *Router) GlobalPanicHandler(writer http.ResponseWriter, request *http
//让Router具有处理请求的功能。 //让Router具有处理请求的功能。
func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request) { func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
startTime := time.Now()
//每个请求的入口在这里 //每个请求的入口在这里
//全局异常处理。 //全局异常处理。
defer this.GlobalPanicHandler(writer, request) defer this.GlobalPanicHandler(writer, request, startTime)
path := request.URL.Path path := request.URL.Path
if strings.HasPrefix(path, "/api") { if strings.HasPrefix(path, "/api") {
@ -128,7 +134,7 @@ func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)
} }
//正常的访问记录会落到这里。 //正常的访问记录会落到这里。
go this.footprintService.Trace(writer, request) go this.footprintService.Trace(writer, request, time.Now().Sub(startTime), true)
} else { } else {
//当作静态资源处理。默认从当前文件下面的static文件夹中取东西。 //当作静态资源处理。默认从当前文件下面的static文件夹中取东西。

View File

@ -62,9 +62,9 @@ func (this *UserController) Login(writer http.ResponseWriter, request *http.Requ
} }
} }
//登录成功设置Cookie。有效期7天。 //登录成功设置Cookie。有效期30天。
expiration := time.Now() expiration := time.Now()
expiration = expiration.AddDate(0, 0, 7) expiration = expiration.AddDate(0, 0, 30)
//持久化用户的session. //持久化用户的session.
session := &Session{ session := &Session{

View File

@ -44,8 +44,6 @@ func (this *UserService) bootstrap(writer http.ResponseWriter, request *http.Req
sessionId := sessionCookie.Value sessionId := sessionCookie.Value
this.logger.Info("请求的sessionId = " + sessionId)
//去缓存中捞取 //去缓存中捞取
cacheItem, err := CONTEXT.SessionCache.Value(sessionId) cacheItem, err := CONTEXT.SessionCache.Value(sessionId)
if err != nil { if err != nil {
@ -64,7 +62,6 @@ func (this *UserService) bootstrap(writer http.ResponseWriter, request *http.Req
if user != nil { if user != nil {
//将用户装填进缓存中 //将用户装填进缓存中
CONTEXT.SessionCache.Add(sessionCookie.Value, duration, user) CONTEXT.SessionCache.Add(sessionCookie.Value, duration, user)
} else { } else {
this.logger.Error("没有找到对应的user " + session.UserUuid) this.logger.Error("没有找到对应的user " + session.UserUuid)
} }