package main

import (
	"fmt"
	"goweb/models"
	"goweb/routers"
	"html/template"
	"net/http"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"github.com/unrolled/secure"
)

func main() {
	yaml := models.YmlRead{}
	yml, _ := yaml.Read("conf/app.yml")
	myttps := fmt.Sprintf("%v", yml["HttpS"])
	if myttps == "" {
		myttps = "false"
	}

	gin.SetMode(gin.ReleaseMode)
	//r := gin.Default()
	r := gin.New()
	r.SetFuncMap(template.FuncMap{
		"strhtml": func(s string) template.HTML {
			return template.HTML(s)
		},
		"substr": func(s string, start int, end int) string {
			return s[start:end]
		},
	})
	//静态目录 css js
	r.Static("static", "static")
	//前端多级目录views/admin/xxx.html
	r.LoadHTMLGlob("views/**/**/*")
	//文件服务器
	r.StaticFS("tool", http.Dir("tool"))
	// 创建基于cookie的存储引擎，secret11111 参数是用于加密的密钥
	Store := cookie.NewStore([]byte("360xyz"))
	// 设置session中间件，参数mysession，指的是session的名字，也是cookie的名字
	// store是前面创建的存储引擎，我们可以替换成其他存储引擎
	//session过期时间30分
	Store.Options(sessions.Options{
		MaxAge: 1800,
		Path:   "/",
	})

	r.Use(sessions.Sessions("mysession", Store))
	//调用路由
	routers.GinRouterInit(r)

	if myttps == "true" {
		https := gin.New()
		https.SetFuncMap(template.FuncMap{
			"strhtml": func(s string) template.HTML {
				return template.HTML(s)
			},
			"substr": func(s string, start int, end int) string {
				return s[start:end]
			},
		})
		https.Static("static", "static")
		https.LoadHTMLGlob("views/**/**/*")
		https.Use(sessions.Sessions("mysession", Store))
		routers.GinRouterInit(https)
		https.Use(func(ctx *gin.Context) {
			secureMiddleware := secure.New(secure.Options{
				SSLRedirect: true,
				SSLHost:     "localhost:443",
			})
			err := secureMiddleware.Process(ctx.Writer, ctx.Request)
			if err != nil {
				return
			}
			ctx.Next()
		})
		go func() {
			err7 := http.ListenAndServeTLS(":"+fmt.Sprintf("%v", yml["HttpsPort"]), fmt.Sprintf("%v", yml["certFile"]), fmt.Sprintf("%v", yml["keyFile"]), https)
			if err7 != nil {
				fmt.Println("httpsError")
			}
		}()
	}
	//不指定端口，默认8080
	r.Run(":80")

}
