refactor: eiblog

This commit is contained in:
deepzz0
2021-04-26 15:51:16 +08:00
parent bd69c62254
commit 68e01cdf1f
843 changed files with 3606 additions and 1007377 deletions

55
pkg/mid/language.go Normal file
View File

@@ -0,0 +1,55 @@
// Package mid provides ...
package mid
import (
"strings"
"github.com/gin-gonic/gin"
)
// LangOpts 语言选项
type LangOpts struct {
CookieName string
Default string
Supported []string
}
// isExist language
func (opts LangOpts) isExist(l string) bool {
for _, v := range opts.Supported {
if v == l {
return true
}
}
return false
}
// LangMiddleware set language
func LangMiddleware(opts LangOpts) gin.HandlerFunc {
return func(c *gin.Context) {
lang, err := c.Cookie(opts.CookieName)
// found cookie
if err == nil {
c.Set(opts.CookieName, lang)
return
}
// set cookie
al := strings.ToLower(c.GetHeader("Accept-Language"))
if al != "" {
// choose default if not supported
lang = opts.Default
langs := strings.Split(al, ",")
for _, v := range langs {
if opts.isExist(v) {
lang = v
break
}
}
} else {
lang = opts.Default
}
c.SetCookie(opts.CookieName, lang, 86400*365, "/", "", false, false)
c.Set(opts.CookieName, lang)
}
}

34
pkg/mid/session.go Normal file
View File

@@ -0,0 +1,34 @@
// Package mid provides ...
package mid
import (
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
)
// SessionOpts 设置选项
type SessionOpts struct {
Name string
Secure bool // required
Secret []byte // required
// redis store
RedisAddr string
RedisPwd string
}
// SessionMiddleware session中间件
func SessionMiddleware(opts SessionOpts) gin.HandlerFunc {
store := cookie.NewStore(opts.Secret)
store.Options(sessions.Options{
MaxAge: 86400 * 30,
Path: "/",
Secure: opts.Secure,
HttpOnly: true,
})
name := "SESSIONID"
if opts.Name != "" {
name = opts.Name
}
return sessions.Sessions(name, store)
}

18
pkg/mid/u.go Normal file
View File

@@ -0,0 +1,18 @@
// Package mid provides ...
package mid
import (
"github.com/gin-gonic/gin"
"github.com/gofrs/uuid"
)
// UserMiddleware 用户cookie标记
func UserMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
cookie, err := c.Cookie("u")
if err != nil || cookie == "" {
u1 := uuid.Must(uuid.NewV4()).String()
c.SetCookie("u", u1, 86400*730, "/", "", true, true)
}
}
}