Compare commits

..

No commits in common. "0faac992cfe36bd54edae3f4abe0a2eecb8d72f8" and "7d95109e786b1916ede9b2b9fba520fc1a2a08ed" have entirely different histories.

32 changed files with 282 additions and 273 deletions

View File

@ -8,7 +8,7 @@ import (
) )
type MemoryMapCache[K comparable, V any] struct { type MemoryMapCache[K comparable, V any] struct {
*safety.Map[K, mapVal[V]] safety.Map[K, mapVal[V]]
} }
func NewMemoryMapCacheByFn[K comparable, V any](fn func(...any) (V, error), expireTime time.Duration) *MapCache[K, V] { func NewMemoryMapCacheByFn[K comparable, V any](fn func(...any) (V, error), expireTime time.Duration) *MapCache[K, V] {

2
cache/vars.go vendored
View File

@ -10,7 +10,7 @@ import (
) )
type VarCache[T any] struct { type VarCache[T any] struct {
v *safety.Var[vars[T]] v safety.Var[vars[T]]
} }
type vars[T any] struct { type vars[T any] struct {

View File

@ -1,53 +0,0 @@
package cachemanager
import (
"context"
"github.com/fthvgb1/wp-go/cache"
"time"
)
var ctx = context.Background()
type flush interface {
Flush(ctx context.Context)
}
type clear interface {
ClearExpired(ctx context.Context)
}
var clears []clear
var flushes []flush
func Flush() {
for _, f := range flushes {
f.Flush(ctx)
}
}
func MapCacheBy[K comparable, V any](fn func(...any) (V, error), expireTime time.Duration) *cache.MapCache[K, V] {
m := cache.NewMemoryMapCacheByFn[K, V](fn, expireTime)
FlushPush(m)
ClearPush(m)
return m
}
func MapBatchCacheBy[K comparable, V any](fn func(...any) (map[K]V, error), expireTime time.Duration) *cache.MapCache[K, V] {
m := cache.NewMemoryMapCacheByBatchFn[K, V](fn, expireTime)
FlushPush(m)
ClearPush(m)
return m
}
func FlushPush(f ...flush) {
flushes = append(flushes, f...)
}
func ClearPush(c ...clear) {
clears = append(clears, c...)
}
func ClearExpired() {
for _, c := range clears {
c.ClearExpired(ctx)
}
}

View File

@ -3,8 +3,6 @@ package main
import ( import (
"flag" "flag"
"fmt" "fmt"
"github.com/fthvgb1/wp-go/internal/cmd/cachemanager"
"github.com/fthvgb1/wp-go/internal/cmd/reload"
"github.com/fthvgb1/wp-go/internal/cmd/route" "github.com/fthvgb1/wp-go/internal/cmd/route"
"github.com/fthvgb1/wp-go/internal/mail" "github.com/fthvgb1/wp-go/internal/mail"
"github.com/fthvgb1/wp-go/internal/pkg/cache" "github.com/fthvgb1/wp-go/internal/pkg/cache"
@ -27,6 +25,7 @@ import (
var confPath string var confPath string
var address string var address string
var middleWareReloadFn func()
var intReg = regexp.MustCompile(`^\d`) var intReg = regexp.MustCompile(`^\d`)
func init() { func init() {
@ -77,7 +76,8 @@ func cronClearCache() {
for { for {
select { select {
case <-t.C: case <-t.C:
cachemanager.ClearExpired() cache.ClearCache()
plugins.ClearDigestCache()
} }
} }
} }
@ -89,11 +89,12 @@ func flushCache() {
logs.ErrPrintln(err, "发邮件失败") logs.ErrPrintln(err, "发邮件失败")
} }
}() }()
cachemanager.Flush() cache.FlushCache()
plugins.FlushCache()
log.Println("all cache flushed") log.Println("all cache flushed")
} }
func reloads() { func reload() {
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {
log.Println(r) log.Println(r)
@ -104,8 +105,12 @@ func reloads() {
err = wpconfig.InitOptions() err = wpconfig.InitOptions()
logs.ErrPrintln(err, "获取网站设置WpOption失败") logs.ErrPrintln(err, "获取网站设置WpOption失败")
err = wpconfig.InitTerms() err = wpconfig.InitTerms()
wpconfig.FlushModes()
theme.Reload()
logs.ErrPrintln(err, "获取WpTerms表失败") logs.ErrPrintln(err, "获取WpTerms表失败")
reload.Reload() if middleWareReloadFn != nil {
middleWareReloadFn()
}
flushCache() flushCache()
log.Println("reload complete") log.Println("reload complete")
} }
@ -116,7 +121,7 @@ func signalNotify() {
for { for {
switch <-c { switch <-c {
case syscall.SIGUSR1: case syscall.SIGUSR1:
go reloads() go reload()
case syscall.SIGUSR2: case syscall.SIGUSR2:
go flushCache() go flushCache()
} }
@ -125,8 +130,9 @@ func signalNotify() {
func main() { func main() {
go signalNotify() go signalNotify()
Gin := route.SetupRouter() Gin, reloadFn := route.SetupRouter()
c := config.GetConfig() c := config.GetConfig()
middleWareReloadFn = reloadFn
if c.Ssl.Key != "" && c.Ssl.Cert != "" { if c.Ssl.Key != "" && c.Ssl.Cert != "" {
err := Gin.RunTLS(address, c.Ssl.Cert, c.Ssl.Key) err := Gin.RunTLS(address, c.Ssl.Cert, c.Ssl.Key)
if err != nil { if err != nil {

View File

@ -1,30 +0,0 @@
package reload
import "github.com/fthvgb1/wp-go/safety"
var calls []func()
func Vars[T any](defaults T) *safety.Var[T] {
ss := safety.NewVar(defaults)
calls = append(calls, func() {
ss.Store(defaults)
})
return ss
}
func VarsBy[T any](fn func() T) *safety.Var[T] {
ss := safety.NewVar(fn())
calls = append(calls, func() {
ss.Store(fn())
})
return ss
}
func Push(fn ...func()) {
calls = append(calls, fn...)
}
func Reload() {
for _, call := range calls {
call()
}
}

View File

@ -2,7 +2,6 @@ package route
import ( import (
"github.com/fthvgb1/wp-go/internal/actions" "github.com/fthvgb1/wp-go/internal/actions"
"github.com/fthvgb1/wp-go/internal/cmd/reload"
"github.com/fthvgb1/wp-go/internal/middleware" "github.com/fthvgb1/wp-go/internal/middleware"
"github.com/fthvgb1/wp-go/internal/pkg/config" "github.com/fthvgb1/wp-go/internal/pkg/config"
"github.com/fthvgb1/wp-go/internal/pkg/constraints" "github.com/fthvgb1/wp-go/internal/pkg/constraints"
@ -17,7 +16,7 @@ import (
"net/http" "net/http"
) )
func SetupRouter() *gin.Engine { func SetupRouter() (*gin.Engine, func()) {
// Disable Console Color // Disable Console Color
// gin.DisableConsoleColor() // gin.DisableConsoleColor()
r := gin.New() r := gin.New()
@ -31,12 +30,14 @@ func SetupRouter() *gin.Engine {
r.HTMLRender = theme.GetTemplate() r.HTMLRender = theme.GetTemplate()
wpconfig.SetTemplateFs(theme.TemplateFs) wpconfig.SetTemplateFs(theme.TemplateFs)
siteFlowLimitMiddleware, siteFlow := middleware.FlowLimit(c.MaxRequestSleepNum, c.MaxRequestNum, c.CacheTime.SleepTime)
validServerName, reloadValidServerNameFn := middleware.ValidateServerNames()
fl, flReload := middleware.FlowLimit(c.MaxRequestSleepNum, c.MaxRequestNum, c.CacheTime.SleepTime)
r.Use( r.Use(
gin.Logger(), gin.Logger(),
middleware.ValidateServerNames(), validServerName,
middleware.RecoverAndSendMail(gin.DefaultErrorWriter), middleware.RecoverAndSendMail(gin.DefaultErrorWriter),
siteFlowLimitMiddleware, fl,
middleware.SetStaticFileCache, middleware.SetStaticFileCache,
) )
//gzip 因为一般会用nginx做反代时自动使用gzip,所以go这边本身可以不用 //gzip 因为一般会用nginx做反代时自动使用gzip,所以go这边本身可以不用
@ -62,7 +63,8 @@ func SetupRouter() *gin.Engine {
} }
store := cookie.NewStore([]byte("secret")) store := cookie.NewStore([]byte("secret"))
r.Use(sessions.Sessions("go-wp", store)) r.Use(sessions.Sessions("go-wp", store))
r.GET("/", middleware.SearchLimit(c.SingleIpSearchNum), actions.ThemeHook(constraints.Home)) sl, slRload := middleware.SearchLimit(c.SingleIpSearchNum)
r.GET("/", sl, actions.ThemeHook(constraints.Home))
r.GET("/page/:page", actions.ThemeHook(constraints.Home)) r.GET("/page/:page", actions.ThemeHook(constraints.Home))
r.GET("/p/category/:category", actions.ThemeHook(constraints.Category)) r.GET("/p/category/:category", actions.ThemeHook(constraints.Category))
r.GET("/p/category/:category/page/:page", actions.ThemeHook(constraints.Category)) r.GET("/p/category/:category/page/:page", actions.ThemeHook(constraints.Category))
@ -77,14 +79,16 @@ func SetupRouter() *gin.Engine {
r.GET("/p/:id/feed", actions.PostFeed) r.GET("/p/:id/feed", actions.PostFeed)
r.GET("/feed", actions.Feed) r.GET("/feed", actions.Feed)
r.GET("/comments/feed", actions.CommentsFeed) r.GET("/comments/feed", actions.CommentsFeed)
commentMiddleWare, _ := middleware.FlowLimit(c.MaxRequestSleepNum, 5, c.CacheTime.SleepTime) cfl, _ := middleware.FlowLimit(c.MaxRequestSleepNum, 5, c.CacheTime.SleepTime)
r.POST("/comment", commentMiddleWare, actions.PostComment) r.POST("/comment", cfl, actions.PostComment)
if c.Pprof != "" { if c.Pprof != "" {
pprof.Register(r, c.Pprof) pprof.Register(r, c.Pprof)
} }
reload.Push(func() { fn := func() {
reloadValidServerNameFn()
c := config.GetConfig() c := config.GetConfig()
siteFlow(c.MaxRequestSleepNum, c.MaxRequestNum, c.CacheTime.SleepTime) flReload(c.MaxRequestSleepNum, c.MaxRequestNum, c.CacheTime.SleepTime)
}) slRload(c.SingleIpSearchNum)
return r }
return r, fn
} }

View File

@ -1,16 +1,9 @@
package middleware package middleware
import ( import "github.com/gin-gonic/gin"
"github.com/fthvgb1/wp-go/internal/cmd/reload"
"github.com/fthvgb1/wp-go/internal/pkg/config"
"github.com/gin-gonic/gin"
)
func SearchLimit(num int64) func(ctx *gin.Context) { func SearchLimit(num int64) (func(ctx *gin.Context), func(int64)) {
fn, reFn := IpLimit(num) fn, reFn := IpLimit(num)
reload.Push(func() {
reFn(config.GetConfig().SingleIpSearchNum)
})
return func(c *gin.Context) { return func(c *gin.Context) {
if c.Query("s") != "" { if c.Query("s") != "" {
fn(c) fn(c)
@ -18,5 +11,5 @@ func SearchLimit(num int64) func(ctx *gin.Context) {
c.Next() c.Next()
} }
} }, reFn
} }

View File

@ -1,33 +1,35 @@
package middleware package middleware
import ( import (
"github.com/fthvgb1/wp-go/helper/maps"
"github.com/fthvgb1/wp-go/internal/cmd/reload"
"github.com/fthvgb1/wp-go/internal/pkg/config" "github.com/fthvgb1/wp-go/internal/pkg/config"
"github.com/fthvgb1/wp-go/safety"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"net/http" "net/http"
"strings" "strings"
) )
func ValidateServerNames() func(ctx *gin.Context) { func ValidateServerNames() (func(ctx *gin.Context), func()) {
sites := reload.VarsBy(func() map[string]struct{} { var serverName safety.Map[string, struct{}]
fn := func() {
r := config.GetConfig().TrustServerNames r := config.GetConfig().TrustServerNames
m := map[string]struct{}{}
if len(r) > 0 { if len(r) > 0 {
for _, name := range r { for _, name := range r {
m[name] = struct{}{} serverName.Store(name, struct{}{})
} }
} else {
serverName.Flush()
} }
return m
})
}
fn()
return func(c *gin.Context) { return func(c *gin.Context) {
m := sites.Load() if serverName.Len() > 0 {
if len(m) > 0 && !maps.IsExists(m, strings.Split(c.Request.Host, ":")[0]) { if _, ok := serverName.Load(strings.Split(c.Request.Host, ":")[0]); !ok {
c.Status(http.StatusForbidden) c.Status(http.StatusForbidden)
c.Abort() c.Abort()
return return
} }
}
c.Next() c.Next()
} }, fn
} }

View File

@ -5,7 +5,6 @@ import (
"github.com/fthvgb1/wp-go/cache" "github.com/fthvgb1/wp-go/cache"
"github.com/fthvgb1/wp-go/helper" "github.com/fthvgb1/wp-go/helper"
"github.com/fthvgb1/wp-go/helper/slice" "github.com/fthvgb1/wp-go/helper/slice"
"github.com/fthvgb1/wp-go/internal/cmd/cachemanager"
"github.com/fthvgb1/wp-go/internal/pkg/config" "github.com/fthvgb1/wp-go/internal/pkg/config"
"github.com/fthvgb1/wp-go/internal/pkg/constraints" "github.com/fthvgb1/wp-go/internal/pkg/constraints"
"github.com/fthvgb1/wp-go/internal/pkg/dao" "github.com/fthvgb1/wp-go/internal/pkg/dao"
@ -55,17 +54,17 @@ func InitActionsCommonCache() {
fn: dao.Archives, fn: dao.Archives,
} }
searchPostIdsCache = cachemanager.MapCacheBy[string](dao.SearchPostIds, c.CacheTime.SearchPostCacheTime) searchPostIdsCache = cache.NewMemoryMapCacheByFn[string](dao.SearchPostIds, c.CacheTime.SearchPostCacheTime)
postListIdsCache = cachemanager.MapCacheBy[string](dao.SearchPostIds, c.CacheTime.PostListCacheTime) postListIdsCache = cache.NewMemoryMapCacheByFn[string](dao.SearchPostIds, c.CacheTime.PostListCacheTime)
monthPostsCache = cachemanager.MapCacheBy[string](dao.MonthPost, c.CacheTime.MonthPostCacheTime) monthPostsCache = cache.NewMemoryMapCacheByFn[string](dao.MonthPost, c.CacheTime.MonthPostCacheTime)
postContextCache = cachemanager.MapCacheBy[uint64](dao.GetPostContext, c.CacheTime.ContextPostCacheTime) postContextCache = cache.NewMemoryMapCacheByFn[uint64](dao.GetPostContext, c.CacheTime.ContextPostCacheTime)
postsCache = cachemanager.MapBatchCacheBy(dao.GetPostsByIds, c.CacheTime.PostDataCacheTime) postsCache = cache.NewMemoryMapCacheByBatchFn(dao.GetPostsByIds, c.CacheTime.PostDataCacheTime)
postMetaCache = cachemanager.MapBatchCacheBy(dao.GetPostMetaByPostIds, c.CacheTime.PostDataCacheTime) postMetaCache = cache.NewMemoryMapCacheByBatchFn(dao.GetPostMetaByPostIds, c.CacheTime.PostDataCacheTime)
categoryAndTagsCaches = cache.NewVarCache(dao.CategoriesAndTags, c.CacheTime.CategoryCacheTime) categoryAndTagsCaches = cache.NewVarCache(dao.CategoriesAndTags, c.CacheTime.CategoryCacheTime)
@ -73,33 +72,63 @@ func InitActionsCommonCache() {
recentCommentsCaches = cache.NewVarCache(dao.RecentComments, c.CacheTime.RecentCommentsCacheTime) recentCommentsCaches = cache.NewVarCache(dao.RecentComments, c.CacheTime.RecentCommentsCacheTime)
postCommentCaches = cachemanager.MapCacheBy[uint64](dao.PostComments, c.CacheTime.PostCommentsCacheTime) postCommentCaches = cache.NewMemoryMapCacheByFn[uint64](dao.PostComments, c.CacheTime.PostCommentsCacheTime)
maxPostIdCache = cache.NewVarCache(dao.GetMaxPostId, c.CacheTime.MaxPostIdCacheTime) maxPostIdCache = cache.NewVarCache(dao.GetMaxPostId, c.CacheTime.MaxPostIdCacheTime)
usersCache = cachemanager.MapCacheBy[uint64](dao.GetUserById, c.CacheTime.UserInfoCacheTime) usersCache = cache.NewMemoryMapCacheByFn[uint64](dao.GetUserById, c.CacheTime.UserInfoCacheTime)
usersNameCache = cachemanager.MapCacheBy[string](dao.GetUserByName, c.CacheTime.UserInfoCacheTime) usersNameCache = cache.NewMemoryMapCacheByFn[string](dao.GetUserByName, c.CacheTime.UserInfoCacheTime)
commentsCache = cachemanager.MapBatchCacheBy(dao.GetCommentByIds, c.CacheTime.CommentsCacheTime) commentsCache = cache.NewMemoryMapCacheByBatchFn(dao.GetCommentByIds, c.CacheTime.CommentsCacheTime)
allUsernameCache = cache.NewVarCache(dao.AllUsername, c.CacheTime.UserInfoCacheTime) allUsernameCache = cache.NewVarCache(dao.AllUsername, c.CacheTime.UserInfoCacheTime)
headerImagesCache = cachemanager.MapCacheBy[string](getHeaderImages, c.CacheTime.ThemeHeaderImagCacheTime) headerImagesCache = cache.NewMemoryMapCacheByFn[string](getHeaderImages, c.CacheTime.ThemeHeaderImagCacheTime)
feedCache = cache.NewVarCache(feed, time.Hour) feedCache = cache.NewVarCache(feed, time.Hour)
postFeedCache = cachemanager.MapCacheBy[string](postFeed, time.Hour) postFeedCache = cache.NewMemoryMapCacheByFn[string](postFeed, time.Hour)
commentsFeedCache = cache.NewVarCache(commentsFeed, time.Hour) commentsFeedCache = cache.NewVarCache(commentsFeed, time.Hour)
newCommentCache = cachemanager.MapCacheBy[string, string](nil, 15*time.Minute) newCommentCache = cache.NewMemoryMapCacheByFn[string, string](nil, 15*time.Minute)
ctx = context.Background() ctx = context.Background()
InitFeed() InitFeed()
} }
func ClearCache() {
searchPostIdsCache.ClearExpired(ctx)
searchPostIdsCache.ClearExpired(ctx)
postsCache.ClearExpired(ctx)
postMetaCache.ClearExpired(ctx)
postListIdsCache.ClearExpired(ctx)
monthPostsCache.ClearExpired(ctx)
postContextCache.ClearExpired(ctx)
usersCache.ClearExpired(ctx)
commentsCache.ClearExpired(ctx)
usersNameCache.ClearExpired(ctx)
postFeedCache.ClearExpired(ctx)
newCommentCache.ClearExpired(ctx)
headerImagesCache.ClearExpired(ctx)
}
func FlushCache() {
searchPostIdsCache.Flush(ctx)
postsCache.Flush(ctx)
postMetaCache.Flush(ctx)
postListIdsCache.Flush(ctx)
monthPostsCache.Flush(ctx)
postContextCache.Flush(ctx)
usersCache.Flush(ctx)
commentsCache.Flush(ctx)
usersCache.Flush(ctx)
postFeedCache.Flush(ctx)
newCommentCache.Flush(ctx)
headerImagesCache.Flush(ctx)
}
func Archives(ctx context.Context) (r []models.PostArchive) { func Archives(ctx context.Context) (r []models.PostArchive) {
return archivesCaches.getArchiveCache(ctx) return archivesCaches.getArchiveCache(ctx)
} }

View File

@ -13,6 +13,4 @@ const (
Error404 Error404
ParamError ParamError
InternalErr InternalErr
Defaults = "default"
) )

View File

@ -4,7 +4,6 @@ import (
"context" "context"
"fmt" "fmt"
"github.com/fthvgb1/wp-go/cache" "github.com/fthvgb1/wp-go/cache"
"github.com/fthvgb1/wp-go/internal/cmd/cachemanager"
"github.com/fthvgb1/wp-go/internal/pkg/config" "github.com/fthvgb1/wp-go/internal/pkg/config"
"github.com/fthvgb1/wp-go/internal/pkg/models" "github.com/fthvgb1/wp-go/internal/pkg/models"
"github.com/fthvgb1/wp-go/plugin/digest" "github.com/fthvgb1/wp-go/plugin/digest"
@ -13,9 +12,18 @@ import (
) )
var digestCache *cache.MapCache[uint64, string] var digestCache *cache.MapCache[uint64, string]
var ctx context.Context
func InitDigestCache() { func InitDigestCache() {
digestCache = cachemanager.MapCacheBy[uint64](digestRaw, config.GetConfig().CacheTime.DigestCacheTime) ctx = context.Background()
digestCache = cache.NewMemoryMapCacheByFn[uint64](digestRaw, config.GetConfig().CacheTime.DigestCacheTime)
}
func ClearDigestCache() {
digestCache.ClearExpired(ctx)
}
func FlushCache() {
digestCache.Flush(ctx)
} }
func digestRaw(arg ...any) (string, error) { func digestRaw(arg ...any) (string, error) {

View File

@ -1,13 +1,12 @@
package twentyfifteen package common
import ( import (
"fmt" "fmt"
"github.com/fthvgb1/wp-go/helper" "github.com/fthvgb1/wp-go/helper"
"github.com/fthvgb1/wp-go/helper/maps" "github.com/fthvgb1/wp-go/helper/maps"
str "github.com/fthvgb1/wp-go/helper/strings" str "github.com/fthvgb1/wp-go/helper/strings"
"github.com/fthvgb1/wp-go/internal/cmd/reload"
"github.com/fthvgb1/wp-go/internal/pkg/constraints"
"github.com/fthvgb1/wp-go/internal/wpconfig" "github.com/fthvgb1/wp-go/internal/wpconfig"
"github.com/fthvgb1/wp-go/safety"
) )
var postx = map[string]string{ var postx = map[string]string{
@ -32,45 +31,45 @@ var repeat = map[string]string{
"no-repeat": "no-repeat", "no-repeat": "no-repeat",
} }
var backgroud = reload.Vars(constraints.Defaults) var backgroud = safety.NewVar("default")
func (h *handle) CustomBackGround() { func (h *Handle) CustomBackGround() {
b := backgroud.Load() b := backgroud.Load()
if b == constraints.Defaults { if b == "default" {
b = h.CalCustomBackGround() b = h.CalCustomBackGround()
backgroud.Store(b) backgroud.Store(b)
} }
h.IndexHandle.GinH["customBackground"] = b h.GinH["customBackground"] = b
} }
func (h *handle) CalCustomBackGround() (r string) { func (h *Handle) CalCustomBackGround() (r string) {
mods, err := wpconfig.GetThemeMods(h.IndexHandle.Theme) mods, err := wpconfig.GetThemeMods(h.Theme)
if err != nil { if err != nil {
return return
} }
if mods.BackgroundImage == "" && mods.BackgroundColor == themesupport.CustomBackground.DefaultColor { if mods.BackgroundImage == "" && mods.BackgroundColor == mods.ThemeSupport.CustomBackground.DefaultColor {
return return
} }
s := str.NewBuilder() s := str.NewBuilder()
if mods.BackgroundImage != "" { if mods.BackgroundImage != "" {
s.Sprintf(` background-image: url("%s");`, helper.CutUrlHost(mods.BackgroundImage)) s.Sprintf(` background-image: url("%s");`, helper.CutUrlHost(mods.BackgroundImage))
} }
backgroundPositionX := helper.Defaults(mods.BackgroundPositionX, themesupport.CustomBackground.DefaultPositionX) backgroundPositionX := helper.Defaults(mods.BackgroundPositionX, mods.ThemeSupport.CustomBackground.DefaultPositionX)
backgroundPositionX = maps.WithDefaultVal(postx, backgroundPositionX, "left") backgroundPositionX = maps.WithDefaultVal(postx, backgroundPositionX, "left")
backgroundPositionY := helper.Defaults(mods.BackgroundPositionY, themesupport.CustomBackground.DefaultPositionY) backgroundPositionY := helper.Defaults(mods.BackgroundPositionY, mods.ThemeSupport.CustomBackground.DefaultPositionY)
backgroundPositionY = maps.WithDefaultVal(posty, backgroundPositionY, "top") backgroundPositionY = maps.WithDefaultVal(posty, backgroundPositionY, "top")
positon := fmt.Sprintf(" background-position: %s %s;", backgroundPositionX, backgroundPositionY) positon := fmt.Sprintf(" background-position: %s %s;", backgroundPositionX, backgroundPositionY)
siz := helper.DefaultVal(mods.BackgroundSize, themesupport.CustomBackground.DefaultSize) siz := helper.DefaultVal(mods.BackgroundSize, mods.ThemeSupport.CustomBackground.DefaultSize)
siz = maps.WithDefaultVal(size, siz, "auto") siz = maps.WithDefaultVal(size, siz, "auto")
siz = fmt.Sprintf(" background-size: %s;", siz) siz = fmt.Sprintf(" background-size: %s;", siz)
repeats := helper.Defaults(mods.BackgroundRepeat, themesupport.CustomBackground.DefaultRepeat) repeats := helper.Defaults(mods.BackgroundRepeat, mods.ThemeSupport.CustomBackground.DefaultRepeat)
repeats = maps.WithDefaultVal(repeat, repeats, "repeat") repeats = maps.WithDefaultVal(repeat, repeats, "repeat")
repeats = fmt.Sprintf(" background-repeat: %s;", repeats) repeats = fmt.Sprintf(" background-repeat: %s;", repeats)
attachment := helper.Defaults(mods.BackgroundAttachment, themesupport.CustomBackground.DefaultAttachment) attachment := helper.Defaults(mods.BackgroundAttachment, mods.ThemeSupport.CustomBackground.DefaultAttachment)
attachment = helper.Or(attachment == "fixed", "fixed", "scroll") attachment = helper.Or(attachment == "fixed", "fixed", "scroll")
attachment = fmt.Sprintf(" background-attachment: %s;", attachment) attachment = fmt.Sprintf(" background-attachment: %s;", attachment)
s.WriteString(positon, siz, repeats, attachment) s.WriteString(positon, siz, repeats, attachment)

View File

@ -3,13 +3,12 @@ package common
import ( import (
"fmt" "fmt"
"github.com/fthvgb1/wp-go/helper/html" "github.com/fthvgb1/wp-go/helper/html"
"github.com/fthvgb1/wp-go/internal/cmd/reload"
"github.com/fthvgb1/wp-go/internal/pkg/cache" "github.com/fthvgb1/wp-go/internal/pkg/cache"
"github.com/fthvgb1/wp-go/internal/pkg/constraints"
"github.com/fthvgb1/wp-go/internal/wpconfig" "github.com/fthvgb1/wp-go/internal/wpconfig"
"github.com/fthvgb1/wp-go/safety"
) )
var css = reload.Vars(constraints.Defaults) var css = safety.NewVar("default")
func (h *Handle) CalCustomCss() (r string) { func (h *Handle) CalCustomCss() (r string) {
mods, err := wpconfig.GetThemeMods(h.Theme) mods, err := wpconfig.GetThemeMods(h.Theme)
@ -26,7 +25,7 @@ func (h *Handle) CalCustomCss() (r string) {
func (h *Handle) CustomCss() { func (h *Handle) CustomCss() {
cs := css.Load() cs := css.Load()
if cs == constraints.Defaults { if cs == "default" {
cs = h.CalCustomCss() cs = h.CalCustomCss()
css.Store(cs) css.Store(cs)
} }

View File

@ -4,13 +4,12 @@ import (
"fmt" "fmt"
"github.com/fthvgb1/wp-go/helper/maps" "github.com/fthvgb1/wp-go/helper/maps"
str "github.com/fthvgb1/wp-go/helper/strings" str "github.com/fthvgb1/wp-go/helper/strings"
"github.com/fthvgb1/wp-go/internal/cmd/reload"
"github.com/fthvgb1/wp-go/internal/pkg/cache" "github.com/fthvgb1/wp-go/internal/pkg/cache"
"github.com/fthvgb1/wp-go/internal/pkg/constraints"
"github.com/fthvgb1/wp-go/internal/wpconfig" "github.com/fthvgb1/wp-go/internal/wpconfig"
"github.com/fthvgb1/wp-go/safety"
) )
var logo = reload.Vars(constraints.Defaults) var logo = safety.NewVar("default")
func (h *Handle) CalCustomLogo() (r string) { func (h *Handle) CalCustomLogo() (r string) {
mods, err := wpconfig.GetThemeMods(h.Theme) mods, err := wpconfig.GetThemeMods(h.Theme)
@ -51,7 +50,7 @@ func (h *Handle) CalCustomLogo() (r string) {
func (h *Handle) CustomLogo() { func (h *Handle) CustomLogo() {
s := logo.Load() s := logo.Load()
if s == constraints.Defaults { if s == "default" {
s = h.CalCustomLogo() s = h.CalCustomLogo()
logo.Store(s) logo.Store(s)
} }

View File

@ -105,6 +105,7 @@ func (d *DetailHandle) Render() {
if d.Templ == "" { if d.Templ == "" {
d.Templ = fmt.Sprintf("%s/posts/detail.gohtml", d.Theme) d.Templ = fmt.Sprintf("%s/posts/detail.gohtml", d.Theme)
} }
d.CustomBackGround()
d.C.HTML(d.Code, d.Templ, d.GinH) d.C.HTML(d.Code, d.Templ, d.GinH)
} }

View File

@ -119,6 +119,7 @@ func (i *IndexHandle) Render() {
if i.Templ == "" { if i.Templ == "" {
i.Templ = fmt.Sprintf("%s/posts/index.gohtml", i.Theme) i.Templ = fmt.Sprintf("%s/posts/index.gohtml", i.Theme)
} }
i.CustomBackGround()
i.C.HTML(i.Code, i.Templ, i.GinH) i.C.HTML(i.Code, i.Templ, i.GinH)
} }

View File

@ -0,0 +1,7 @@
package common
func Reload() {
backgroud.Store("default")
icon.Store("default")
css.Store("default")
}

View File

@ -4,14 +4,13 @@ import (
"fmt" "fmt"
"github.com/fthvgb1/wp-go/helper/slice" "github.com/fthvgb1/wp-go/helper/slice"
str "github.com/fthvgb1/wp-go/helper/strings" str "github.com/fthvgb1/wp-go/helper/strings"
"github.com/fthvgb1/wp-go/internal/cmd/reload"
"github.com/fthvgb1/wp-go/internal/pkg/cache" "github.com/fthvgb1/wp-go/internal/pkg/cache"
"github.com/fthvgb1/wp-go/internal/pkg/constraints"
"github.com/fthvgb1/wp-go/internal/wpconfig" "github.com/fthvgb1/wp-go/internal/wpconfig"
"github.com/fthvgb1/wp-go/safety"
"strings" "strings"
) )
var icon = reload.Vars(constraints.Defaults) var icon = safety.NewVar("default")
var sizes = []string{"site_icon-270", "site_icon-32", "site_icon-192", "site_icon-180"} var sizes = []string{"site_icon-270", "site_icon-32", "site_icon-192", "site_icon-180"}
func (h *Handle) CalSiteIcon() (r string) { func (h *Handle) CalSiteIcon() (r string) {
@ -45,7 +44,7 @@ func (h *Handle) CalSiteIcon() (r string) {
func (h *Handle) SiteIcon() { func (h *Handle) SiteIcon() {
s := icon.Load() s := icon.Load()
if s == constraints.Defaults { if s == "default" {
s = h.CalSiteIcon() s = h.CalSiteIcon()
icon.Store(s) icon.Store(s)
} }

View File

@ -1,4 +1,7 @@
{{define "common/head"}} {{define "common/head"}}
{{if .customBackground}}
{{.customBackground|unescaped}}
{{end}}
{{if .customHeader}} {{if .customHeader}}
{{.customHeader|unescaped}} {{.customHeader|unescaped}}
{{end}} {{end}}

View File

@ -2,6 +2,7 @@ package theme
import ( import (
"github.com/fthvgb1/wp-go/internal/pkg/config" "github.com/fthvgb1/wp-go/internal/pkg/config"
"github.com/fthvgb1/wp-go/internal/theme/common"
"github.com/fthvgb1/wp-go/internal/theme/twentyfifteen" "github.com/fthvgb1/wp-go/internal/theme/twentyfifteen"
"github.com/fthvgb1/wp-go/internal/theme/twentyseventeen" "github.com/fthvgb1/wp-go/internal/theme/twentyseventeen"
"github.com/fthvgb1/wp-go/internal/wpconfig" "github.com/fthvgb1/wp-go/internal/wpconfig"
@ -12,6 +13,11 @@ func InitTheme() {
addThemeHookFunc(twentyseventeen.ThemeName, twentyseventeen.Hook) addThemeHookFunc(twentyseventeen.ThemeName, twentyseventeen.Hook)
} }
func Reload() {
twentyfifteen.Reload()
common.Reload()
}
func GetTemplateName() string { func GetTemplateName() string {
tmlp := config.GetConfig().Theme tmlp := config.GetConfig().Theme
if tmlp == "" { if tmlp == "" {

View File

@ -2,8 +2,7 @@ package twentyfifteen
import ( import (
str "github.com/fthvgb1/wp-go/helper/strings" str "github.com/fthvgb1/wp-go/helper/strings"
"github.com/fthvgb1/wp-go/internal/cmd/reload" "github.com/fthvgb1/wp-go/safety"
"github.com/fthvgb1/wp-go/internal/pkg/constraints"
) )
var style = `<style type="text/css" id="twentyfifteen-header-css">` var style = `<style type="text/css" id="twentyfifteen-header-css">`
@ -80,7 +79,11 @@ var imgStyle = `.site-header {
} }
}` }`
var header = reload.Vars(constraints.Defaults) var header = safety.NewVar("default")
func Reload() {
header.Store("default")
}
func (h *handle) CalCustomHeader() (r string, rand bool) { func (h *handle) CalCustomHeader() (r string, rand bool) {
img, rand := h.IndexHandle.GetCustomHeader() img, rand := h.IndexHandle.GetCustomHeader()
@ -109,7 +112,7 @@ func (h *handle) CalCustomHeader() (r string, rand bool) {
func (h *handle) CustomHeader() { func (h *handle) CustomHeader() {
headers := header.Load() headers := header.Load()
if headers == constraints.Defaults { if headers == "default" {
headerss, rand := h.CalCustomHeader() headerss, rand := h.CalCustomHeader()
headers = headerss headers = headerss
if !rand { if !rand {

View File

@ -60,8 +60,4 @@
{{template "common/head" .}} {{template "common/head" .}}
{{if .customBackground}}
{{.customBackground|unescaped}}
{{end}}
{{end}} {{end}}

View File

@ -1,33 +0,0 @@
package twentyfifteen
type themeSupport struct {
CustomBackground customBackground `json:"custom-background"`
EditorColorPalette []EditorColorPalette `json:"editor-color-palette"`
EditorGradientPresets []EditorGradientPresets `json:"editor-gradient-presets"`
}
type customBackground struct {
DefaultImage string `json:"default-image"`
DefaultPreset string `json:"default-preset"`
DefaultPositionX string `json:"default-position-x"`
DefaultPositionY string `json:"default-position-y"`
DefaultSize string `json:"default-size"`
DefaultRepeat string `json:"default-repeat"`
DefaultAttachment string `json:"default-attachment"`
DefaultColor string `json:"default-color"`
WpHeadCallback string `json:"wp-head-callback"`
AdminHeadCallback string `json:"admin-head-callback"`
AdminPreviewCallback string `json:"admin-preview-callback"`
}
type EditorColorPalette struct {
Name string `json:"name"`
Slug string `json:"slug"`
Color string `json:"color"`
}
type EditorGradientPresets struct {
Name string `json:"name"`
Slug string `json:"slug"`
Gradient string `json:"gradient"`
}
var themesupport = themeSupport{}

View File

@ -37,12 +37,10 @@ func Hook(h *common.Handle) {
func (h *handle) Index() { func (h *handle) Index() {
h.CustomHeader() h.CustomHeader()
h.CustomBackGround()
h.Indexs() h.Indexs()
} }
func (h *handle) Detail() { func (h *handle) Detail() {
h.CustomHeader() h.CustomHeader()
h.CustomBackGround()
h.Details() h.Details()
} }

View File

@ -1,17 +0,0 @@
package twentyseventeen
type themeSupport struct {
}
type EditorColorPalette struct {
Name string `json:"name"`
Slug string `json:"slug"`
Color string `json:"color"`
}
type EditorGradientPresets struct {
Name string `json:"name"`
Slug string `json:"slug"`
Gradient string `json:"gradient"`
}
var themesupport = themeSupport{}

View File

@ -5,7 +5,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/fthvgb1/wp-go/helper/maps" "github.com/fthvgb1/wp-go/helper/maps"
"github.com/fthvgb1/wp-go/internal/cmd/reload"
"github.com/fthvgb1/wp-go/internal/phphelper" "github.com/fthvgb1/wp-go/internal/phphelper"
"github.com/fthvgb1/wp-go/internal/pkg/models" "github.com/fthvgb1/wp-go/internal/pkg/models"
"github.com/fthvgb1/wp-go/safety" "github.com/fthvgb1/wp-go/safety"
@ -104,13 +103,11 @@ func Thumbnail(metadata models.WpAttachmentMetadata, Type, host string, except .
return return
} }
var themeModes = func() *safety.Map[string, ThemeMod] { var themeModes = safety.Map[string, ThemeMod]{}
m := safety.NewMap[string, ThemeMod]()
reload.Push(func() { func FlushModes() {
m.Flush() themeModes.Flush()
}) }
return m
}()
func GetThemeMods(theme string) (r ThemeMod, err error) { func GetThemeMods(theme string) (r ThemeMod, err error) {
r, ok := themeModes.Load(theme) r, ok := themeModes.Load(theme)

View File

@ -4,17 +4,22 @@ type ThemeSupport struct {
CoreBlockPatterns bool `json:"core-block-patterns"` CoreBlockPatterns bool `json:"core-block-patterns"`
WidgetsBlockEditor bool `json:"widgets-block-editor"` WidgetsBlockEditor bool `json:"widgets-block-editor"`
AutomaticFeedLinks bool `json:"automatic-feed-links"` AutomaticFeedLinks bool `json:"automatic-feed-links"`
TitleTag bool `json:"title-tag"` TitleTag bool
CustomLineHeight bool `json:"title-tag"`
PostThumbnails bool `json:"post-thumbnails"` PostThumbnails bool `json:"post-thumbnails"`
Menus bool `json:"menus"` Menus bool `json:"menus"`
HTML5 []string `json:"html5"` HTML5 []string `json:"html5"`
PostFormats []string `json:"post-formats"` PostFormats []string `json:"post-formats"`
CustomLogo CustomLogo `json:"custom-logo"` CustomLogo CustomLogo `json:"custom-logo"`
CustomizeSelectiveRefreshWidgets bool `json:"customize-selective-refresh-widgets"` CustomBackground CustomBackground `json:"custom-background"`
EditorStyle bool `json:"editor-style"` EditorStyle bool `json:"editor-style"`
EditorStyles bool `json:"editor-styles"` EditorStyles bool `json:"editor-styles"`
WpBlockStyles bool `json:"wp-block-styles"` WpBlockStyles bool `json:"wp-block-styles"`
ResponsiveEmbeds bool `json:"responsive-embeds"` ResponsiveEmbeds bool `json:"responsive-embeds"`
EditorColorPalette []EditorColorPalette `json:"editor-color-palette"`
EditorGradientPresets []EditorGradientPresets `json:"editor-gradient-presets"`
CustomizeSelectiveRefreshWidgets bool `json:"customize-selective-refresh-widgets"`
StarterContent StarterContent `json:"starter-content"`
CustomHeader CustomHeader `json:"custom-header"` CustomHeader CustomHeader `json:"custom-header"`
Widgets bool `json:"widgets"` Widgets bool `json:"widgets"`
} }
@ -26,7 +31,102 @@ type CustomLogo struct {
HeaderText string `json:"header-text"` HeaderText string `json:"header-text"`
UnlinkHomepageLogo bool `json:"unlink-homepage-logo"` UnlinkHomepageLogo bool `json:"unlink-homepage-logo"`
} }
type Widgets struct {
Sidebar1 []string `json:"sidebar-1"`
Sidebar2 []string `json:"sidebar-2"`
Sidebar3 []string `json:"sidebar-3"`
}
type About struct {
Thumbnail string `json:"thumbnail"`
}
type Contact struct {
Thumbnail string `json:"thumbnail"`
}
type Blog struct {
Thumbnail string `json:"thumbnail"`
}
type HomepageSection struct {
Thumbnail string `json:"thumbnail"`
}
type CustomBackground struct {
DefaultImage string `json:"default-image"`
DefaultPreset string `json:"default-preset"`
DefaultPositionX string `json:"default-position-x"`
DefaultPositionY string `json:"default-position-y"`
DefaultSize string `json:"default-size"`
DefaultRepeat string `json:"default-repeat"`
DefaultAttachment string `json:"default-attachment"`
DefaultColor string `json:"default-color"`
WpHeadCallback string `json:"wp-head-callback"`
AdminHeadCallback string `json:"admin-head-callback"`
AdminPreviewCallback string `json:"admin-preview-callback"`
}
type EditorColorPalette struct {
Name string `json:"name"`
Slug string `json:"slug"`
Color string `json:"color"`
}
type EditorGradientPresets struct {
Name string `json:"name"`
Slug string `json:"slug"`
Gradient string `json:"gradient"`
}
type Posts struct {
Num0 string `json:"0"`
About About `json:"about"`
Contact Contact `json:"contact"`
Blog Blog `json:"blog"`
HomepageSection HomepageSection `json:"homepage-section"`
}
type ImageEspresso struct {
PostTitle string `json:"post_title"`
File string `json:"file"`
}
type ImageSandwich struct {
PostTitle string `json:"post_title"`
File string `json:"file"`
}
type ImageCoffee struct {
PostTitle string `json:"post_title"`
File string `json:"file"`
}
type Attachments struct {
ImageEspresso ImageEspresso `json:"image-espresso"`
ImageSandwich ImageSandwich `json:"image-sandwich"`
ImageCoffee ImageCoffee `json:"image-coffee"`
}
type Option struct {
ShowOnFront string `json:"show_on_front"`
PageOnFront string `json:"page_on_front"`
PageForPosts string `json:"page_for_posts"`
}
type ThemeMods struct {
Panel1 string `json:"panel_1"`
Panel2 string `json:"panel_2"`
Panel3 string `json:"panel_3"`
Panel4 string `json:"panel_4"`
}
type Top struct {
Name string `json:"name"`
Items []string `json:"items"`
}
type Social struct {
Name string `json:"name"`
Items []string `json:"items"`
}
type NavMenus struct {
Top Top `json:"top"`
Social Social `json:"social"`
}
type StarterContent struct {
Widgets Widgets `json:"widgets"`
Posts Posts `json:"posts"`
Attachments Attachments `json:"attachments"`
Options Option `json:"options"`
ThemeMods ThemeMods `json:"theme_mods"`
NavMenus NavMenus `json:"nav_menus"`
}
type CustomHeader struct { type CustomHeader struct {
DefaultImage string `json:"default-image"` DefaultImage string `json:"default-image"`
RandomDefault bool `json:"random-default"` RandomDefault bool `json:"random-default"`

View File

@ -58,8 +58,8 @@ type Map[K comparable, V any] struct {
expunged unsafe.Pointer expunged unsafe.Pointer
} }
func NewMap[K comparable, V any]() *Map[K, V] { func NewMap[K comparable, V any]() Map[K, V] {
return &Map[K, V]{ return Map[K, V]{
expunged: unsafe.Pointer(new(any)), expunged: unsafe.Pointer(new(any)),
} }
} }

View File

@ -16,7 +16,7 @@ func TestMap_Load(t *testing.T) {
m.Store(1, 1) m.Store(1, 1)
type testCase[K comparable, V any] struct { type testCase[K comparable, V any] struct {
name string name string
m *Map[K, V] m Map[K, V]
args args[K] args args[K]
wantValue V wantValue V
wantOk bool wantOk bool

View File

@ -3,7 +3,7 @@ package safety
import "sync" import "sync"
type Slice[T any] struct { type Slice[T any] struct {
*Var[[]T] Var[[]T]
mu sync.Mutex mu sync.Mutex
} }

View File

@ -10,8 +10,8 @@ type Var[T any] struct {
p unsafe.Pointer p unsafe.Pointer
} }
func NewVar[T any](val T) *Var[T] { func NewVar[T any](val T) Var[T] {
return &Var[T]{val: val, p: unsafe.Pointer(&val)} return Var[T]{val: val, p: unsafe.Pointer(&val)}
} }
func (r *Var[T]) Load() T { func (r *Var[T]) Load() T {

View File

@ -39,12 +39,6 @@ func TestVar_Load(t *testing.T) {
} }
}) })
} }
r := NewVar("ff")
fmt.Println(r.Load())
q := r
fmt.Println(q.Load())
q.Store("xx")
fmt.Println(r.Load(), q.Load())
} }
func TestVar_Delete(t *testing.T) { func TestVar_Delete(t *testing.T) {