package main

import (
	"fmt"
	nested "github.com/antonfisher/nested-logrus-formatter"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
	"time"
	"tls-forward/tls"
)

func main() {
	logrus.SetLevel(logrus.InfoLevel)
	//logrus.SetFormatter(&logrus.TextFormatter{
	//	//HideKeys:        true,
	//	TimestampFormat: "2006-01-02 15:04:05.000", //时间格式
	//	FullTimestamp:   true,haox
	//})
	logrus.SetFormatter(&nested.Formatter{
		HideKeys:        true,
		FieldsOrder:     []string{"type"},
		TimestampFormat: "2006-01-02 15:04:05.000", //时间格式
		NoColors:        true,
	})
	// 写入文件

	//src, err := os.OpenFile(fileName+".log", os.O_APPEND|os.O_WRONLY|os.O_CREATE, os.ModeAppend)
	//logrus.SetOutput(src)
	//if err != nil {
	//	fmt.Println("err", err)
	//
	//}

	logWriter := &lumberjack.Logger{
		// 日志输出文件路径
		Filename: "/data/log/tls-forward/tls.log",
		// 日志文件最大 size, 单位是 MB
		MaxSize: 100, // megabytes
		// 最大过期日志保留的个数
		MaxBackups: 3,
		// 保留过期文件的最大时间间隔,单位是天
		MaxAge: 28, //days
		// 是否需要压缩滚动日志, 使用的 gzip 压缩
		Compress: true, // disabled by default
	}
	logrus.SetOutput(logWriter)
	//logrus.SetOutput(io.MultiWriter(logWriter, os.Stdout))
	//logrus.SetOutput(os.Stdout)
	fmt.Println("VERSION 1.0.1")
	r := gin.New() //创建一个默认的路由引擎
	r.Use(LoggerMiddleware())
	r.POST("/tls/forward", tls.Forward)
	r.POST("/tls/forwardios", tls.ForwardIOS)
	r.Run(":58000")
}
func LoggerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		startTime := time.Now()

		//crw := &CustomResponseWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
		//c.Writer = crw
		//// 打印请求信息
		//reqBody, _ := c.GetRawData()
		//logrus.Infof("uri: %s params: %s", c.Request.RequestURI, string(reqBody))
		//c.Request.Body = io.NopCloser(bytes.NewBuffer(reqBody))

		c.Next() // 调用该请求的剩余处理程序

		stopTime := time.Since(startTime)
		spendTime := stopTime.String()
		statusCode := c.Writer.Status()
		//clientIP := c.ClientIP()
		//userAgent := c.Request.UserAgent()
		method := c.Request.Method
		url := c.Request.RequestURI
		Log := logrus.WithFields(logrus.Fields{
			//"HostName": hostName,
			"SpendTime": spendTime,
			"path":      url,
			"Method":    method,
			"status":    statusCode,
			//"Ip": clientIP,
			//"DataSize": dataSize,
			//"UserAgent": userAgent,
		})
		Log.Info()
		//if len(c.Errors) > 0 { // 矿建内部错误
		//	Log.Error(c.Errors.ByType(gin.ErrorTypePrivate))
		//}
		//if statusCode >= 500 {
		//	Log.Error()
		//} else if statusCode >= 400 {
		//	Log.Warn()
		//} else {
		//	Log.Info()
		//}
	}
}
