Skip to content

Commit

Permalink
Version 0.3.13
Browse files Browse the repository at this point in the history
1、HttpContext增加ViewC、WriteStringC、WriteBlobC、WriteJsonC、WriteJsonBlobC方法,以支持传入指定HttpCode
2、调整Redirect(code int, targetUrl string) 为 Redirect(code int, targetUrl string) error,增加error返回值
3、DotWeb增加SetLogger方法,支持接入第三方Logger,需实现logger.AppLog接口
4、新增 example/logger 目录
* 2017-05-16 09:00
  • Loading branch information
devfeel committed May 16, 2017
1 parent b81a973 commit cbf0e88
Show file tree
Hide file tree
Showing 9 changed files with 250 additions and 32 deletions.
44 changes: 35 additions & 9 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,8 @@ func (ctx *HttpContext) IsEnd() bool {

//redirect replies to the request with a redirect to url and with httpcode
//default you can use http.StatusFound
func (ctx *HttpContext) Redirect(code int, targetUrl string) {
ctx.Response.Redirect(code, targetUrl)
func (ctx *HttpContext) Redirect(code int, targetUrl string) error {
return ctx.Response.Redirect(code, targetUrl)
}

/*
Expand Down Expand Up @@ -300,6 +300,12 @@ func (ctx *HttpContext) ReadCookie(name string) (*http.Cookie, error) {

// write view content to response
func (ctx *HttpContext) View(name string) error {
return ctx.ViewC(defaultHttpCode, name)
}

// write (httpCode, view content) to response
func (ctx *HttpContext) ViewC(code int, name string) error {
ctx.SetStatusCode(code)
err := ctx.HttpServer.Renderer().Render(ctx.Response.Writer(), name, ctx.ViewData().GetCurrentMap(), ctx)
if err != nil {
panic(err.Error())
Expand All @@ -319,40 +325,60 @@ func (ctx *HttpContext) Write(code int, content []byte) (int, error) {

// write string content to response
func (ctx *HttpContext) WriteString(contents ...interface{}) (int, error) {
return ctx.WriteStringC(defaultHttpCode, contents...)
}

// write (httpCode, string) to response
func (ctx *HttpContext) WriteStringC(code int, contents ...interface{}) (int, error) {
content := fmt.Sprint(contents...)
if ctx.IsHijack {
return ctx.HijackConn.WriteString(content)
} else {
return ctx.Response.Write(defaultHttpCode, []byte(content))
return ctx.Response.Write(code, []byte(content))
}
}

// write []byte content to response
func (ctx *HttpContext) WriteBlob(contentType string, b []byte) (int, error) {
return ctx.WriteBlobC(defaultHttpCode, contentType, b)
}

// write (httpCode, []byte) to response
func (ctx *HttpContext) WriteBlobC(code int, contentType string, b []byte) (int, error) {
if contentType != "" {
ctx.SetContentType(contentType)
}
if ctx.IsHijack {
return ctx.HijackConn.WriteBlob(b)
} else {
return ctx.Response.Write(defaultHttpCode, b)
return ctx.Response.Write(code, b)
}
}

// write json string to response
//
// write (httpCode, json string) to response
// auto convert interface{} to json string
func (ctx *HttpContext) WriteJson(i interface{}) (int, error) {
return ctx.WriteJsonC(defaultHttpCode, i)
}

// write (httpCode, json string) to response
// auto convert interface{} to json string
func (ctx *HttpContext) WriteJsonC(code int, i interface{}) (int, error) {
b, err := json.Marshal(i)
if err != nil {
return 0, err
}
return ctx.WriteJsonBlob(b)
return ctx.WriteJsonBlobC(code, b)
}

// write json string as []byte to response
// write json []byte to response
func (ctx *HttpContext) WriteJsonBlob(b []byte) (int, error) {
return ctx.WriteBlob(MIMEApplicationJSONCharsetUTF8, b)
return ctx.WriteJsonBlobC(defaultHttpCode, b)
}

// write (httpCode, json []byte) to response
func (ctx *HttpContext) WriteJsonBlobC(code int, b []byte) (int, error) {
return ctx.WriteBlobC(code, MIMEApplicationJSONCharsetUTF8, b)
}

// write jsonp string to response
Expand Down
21 changes: 14 additions & 7 deletions dotweb.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ func New() *DotWeb {
Config: config.NewConfig(),
}
app.HttpServer.setDotApp(app)

//init logger
logger.InitLog()
return app
}

Expand Down Expand Up @@ -138,21 +141,27 @@ func (app *DotWeb) SetPProfConfig(enabledPProf bool, httpport int) {
app.Config.App.PProfPort = httpport
}

//set user logger, the logger must implement logger.AppLog interface
func (app *DotWeb) SetLogger(log logger.AppLog) {
logger.SetLogger(log)
}

//set log root path
func (app *DotWeb) SetLogPath(path string) {
logger.Logger().SetLogPath(path)
logger.SetLogPath(path)
}

//set enabled log flag
func (app *DotWeb) SetEnabledLog(enabledLog bool) {
logger.Logger().SetEnabledLog(enabledLog)
logger.SetEnabledLog(enabledLog)
}

/*启动WebServer
* 需要初始化HttpRoute
* httpPort := 80
*/
func (app *DotWeb) StartServer(httpport int) error {

//添加框架默认路由规则
//默认支持pprof信息查看
app.HttpServer.Router().GET("/dotweb/debug/pprof/:key", initPProf)
Expand Down Expand Up @@ -204,9 +213,7 @@ func (app *DotWeb) StartServer(httpport int) error {
app.Use(&xMiddleware{})

port := ":" + strconv.Itoa(httpport)
if app.Config.App.EnabledLog {
logger.Logger().Log("Dotweb:StartServer["+port+"] begin", LogTarget_HttpServer, LogLevel_Debug)
}
logger.Logger().Log("Dotweb:StartServer["+port+"] begin", LogTarget_HttpServer, LogLevel_Debug)
err := http.ListenAndServe(port, app.HttpServer)
return err
}
Expand All @@ -217,9 +224,9 @@ func (app *DotWeb) StartServerWithConfig(config *config.Config) error {

//log config
if config.App.LogPath != "" {
logger.Logger().SetLogPath(config.App.LogPath)
logger.SetLogPath(config.App.LogPath)
}
logger.Logger().SetEnabledLog(config.App.EnabledLog)
logger.SetEnabledLog(config.App.EnabledLog)

//run mode config
if app.Config.App.RunMode != RunMode_Development && app.Config.App.RunMode != RunMode_Production {
Expand Down
148 changes: 148 additions & 0 deletions example/logger/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package main

import (
"fmt"
"github.com/devfeel/dotweb"
"github.com/devfeel/dotweb/logger"
"os"
"strconv"
"strings"
"syscall"
"time"
)

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

//设置dotserver日志目录
//如果不设置,默认启用,且默认为当前目录
app.SetLogger(NewYLog())
app.SetEnabledLog(true)
app.SetLogPath("d:/gotmp/")

fmt.Println(logger.Logger())

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

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

//启动 监控服务
app.SetPProfConfig(true, 8081)

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

func Index(ctx *dotweb.HttpContext) {
ctx.Response.Header().Set("Content-Type", "text/html; charset=utf-8")
ctx.WriteStringC(201, "index => ", ctx.RouterParams)
}

func InitRoute(server *dotweb.HttpServer) {
server.Router().GET("/", Index)
}

type chanLog struct {
Content string
LogTarget string
}

type yLog struct {
logRootPath string
logChan_Custom chan chanLog
enabledLog bool
}

//create new yLog
func NewYLog() *yLog {
l := &yLog{logChan_Custom: make(chan chanLog, 10000)}
go l.handleCustom()
return l
}

const (
defaultDateFormatForFileName = "2006_01_02"
defaultDateLayout = "2006-01-02"
defaultFullTimeLayout = "2006-01-02 15:04:05.999999"
defaultTimeLayout = "2006-01-02 15:04:05"
)

func (l *yLog) Debug(log string, logTarget string) {
l.Log(log, logTarget, "debug")
}

func (l *yLog) Info(log string, logTarget string) {
l.Log(log, logTarget, "info")
}

func (l *yLog) Warn(log string, logTarget string) {
l.Log(log, logTarget, "warn")
}

func (l *yLog) Error(log string, logTarget string) {
l.Log(log, logTarget, "error")
}

func (l *yLog) Log(log string, logTarget string, logLevel string) {
if l.enabledLog {
chanLog := chanLog{
LogTarget: "yLog_" + logTarget + "_" + logLevel,
Content: log,
}
l.logChan_Custom <- chanLog
}
}

//set log path
func (l *yLog) SetLogPath(rootPath string) {
//设置日志根目录
l.logRootPath = rootPath
if !strings.HasSuffix(l.logRootPath, "/") {
l.logRootPath = l.logRootPath + "/"
}
}

//set enabled log
func (l *yLog) SetEnabledLog(enabledLog bool) {
l.enabledLog = enabledLog
}

//处理日志内部函数
func (l *yLog) handleCustom() {
for {
log := <-l.logChan_Custom
l.writeLog(log, "custom")
}
}

func (l *yLog) writeLog(chanLog chanLog, level string) {
filePath := l.logRootPath + chanLog.LogTarget
switch level {
case "custom":
filePath = filePath + "_" + time.Now().Format(defaultDateFormatForFileName) + ".log"
break
}
log := time.Now().Format(defaultFullTimeLayout) + " " + chanLog.Content
writeFile(filePath, log)
}

func writeFile(logFile string, log string) {
var mode os.FileMode
flag := syscall.O_RDWR | syscall.O_APPEND | syscall.O_CREAT
mode = 0666
logstr := log + "\r\n"
file, err := os.OpenFile(logFile, flag, mode)
defer file.Close()
if err != nil {
fmt.Println(logFile, err)
return
}
//fmt.Print(logstr)
file.WriteString(logstr)
}
7 changes: 5 additions & 2 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func main() {

func Index(ctx *dotweb.HttpContext) {
ctx.Response.Header().Set("Content-Type", "text/html; charset=utf-8")
ctx.WriteString("index => ", ctx.RouterParams)
ctx.WriteStringC(201, "index => ", ctx.RouterParams)
}

func IndexReg(ctx *dotweb.HttpContext) {
Expand All @@ -85,7 +85,10 @@ func DefaultError(ctx *dotweb.HttpContext) {
}

func Redirect(ctx *dotweb.HttpContext) {
ctx.Redirect(http.StatusMovedPermanently, "http://www.baidu.com")
err := ctx.Redirect(http.StatusMovedPermanently, "http://www.baidu.com")
if err != nil {
ctx.WriteString(err)
}
}

func InitRoute(server *dotweb.HttpServer) {
Expand Down
37 changes: 33 additions & 4 deletions logger/logger.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package logger

import (
"fmt"
"github.com/devfeel/dotweb/framework/file"
"reflect"
)

const (
Expand All @@ -24,14 +26,41 @@ type AppLog interface {
var (
appLog AppLog
DefaultLogPath string
EnabledLog bool = true
)

func Logger() AppLog {
return appLog
}

func init() {
DefaultLogPath = file.GetCurrentDirectory()
appLog = NewXLog(DefaultLogPath)
appLog.SetEnabledLog(true) //default enabled log
func SetLogger(logger AppLog) {
appLog = logger
logger.SetLogPath(DefaultLogPath)
logger.SetEnabledLog(EnabledLog)
}

func SetLogPath(path string) {
DefaultLogPath = path
if appLog != nil {
appLog.SetLogPath(path)
}
}

func SetEnabledLog(isLog bool) {
EnabledLog = isLog
if appLog != nil {
appLog.SetEnabledLog(isLog)
}
}

func InitLog() {
if DefaultLogPath == "" {
DefaultLogPath = file.GetCurrentDirectory()
}
if appLog == nil {
appLog = NewXLog()
}

SetLogPath(DefaultLogPath) //set default log path
SetEnabledLog(EnabledLog) //set default enabled log
}
Loading

0 comments on commit cbf0e88

Please sign in to comment.