This commit is contained in:
keven1024
2025-10-19 14:05:17 +08:00
20 changed files with 103 additions and 40 deletions

View File

@@ -0,0 +1,19 @@
package controllers
import (
"backend/internal/utils"
"github.com/labstack/echo/v4"
)
func GetAbout(c echo.Context) error {
return utils.HTTPSuccessHandler(c, map[string]any{
"bg_url": utils.GetEnv("about.bg_url"),
"content": utils.GetEnvMapString("about.content"),
"email": utils.GetEnv("about.email"),
"name": utils.GetEnv("about.name"),
"url": utils.GetEnv("about.url"),
"avatar": utils.GetEnv("about.avatar"),
})
}

View File

@@ -0,0 +1,17 @@
package controllers
import (
"backend/internal/utils"
"github.com/labstack/echo/v4"
)
func GetConfig(c echo.Context) error {
return utils.HTTPSuccessHandler(c, map[string]any{
"site_title": utils.GetEnvMapString("site.title"),
"site_desc": utils.GetEnvMapString("site.desc"),
"site_url": utils.GetEnv("site.url"),
"site_icon": utils.GetEnvWithDefault("site.icon", "/logo.png"),
"site_bg_url": utils.GetEnvWithDefault("site.bg_url", "https://img.fudaoyuan.icu/api/1/random/?scale_min=1.5&webp=true&md=false&format=302"),
})
}

View File

@@ -25,7 +25,7 @@ func DownloadShare(c echo.Context) error {
}
claims := DownloadShareClaims{}
t, err := jwt.ParseWithClaims(token, &claims, func(token *jwt.Token) (interface{}, error) {
return []byte(utils.GetEnv("download_secret")), nil
return []byte(utils.GetEnv("share.download_secret")), nil
})
if err != nil {
return utils.HTTPErrorHandler(c, err)
@@ -96,7 +96,7 @@ func VaildateShare(c echo.Context) error {
})
// Sign and get the complete encoded token as a string using the secret
downloadToken, err := token.SignedString([]byte(utils.GetEnv("download_secret")))
downloadToken, err := token.SignedString([]byte(utils.GetEnv("share.download_secret")))
if err != nil {
return utils.HTTPErrorHandler(c, err)
}

View File

@@ -40,7 +40,7 @@ func CreateUploadTask(c echo.Context) error {
"chunk_size": fileInfo.ChunkSize,
})
}
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("MAX_LOCALSTORAGE_SIZE"))
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("upload.maximum"))
if err != nil {
return utils.HTTPErrorHandler(c, err)
}

View File

@@ -70,7 +70,7 @@ func GetStat(c echo.Context) error {
return utils.HTTPErrorHandler(c, err)
}
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("MAX_LOCALSTORAGE_SIZE"))
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("upload.maximum"))
if err != nil {
return utils.HTTPErrorHandler(c, err)
}

View File

@@ -3,17 +3,17 @@ package utils
import "github.com/hibiken/asynq"
func GetQueueClient() *asynq.Client {
opt := RedisURI2AsynqOpt(GetEnv("REDIS_URL"))
opt := RedisURI2AsynqOpt(GetEnv("redis.url"))
return asynq.NewClient(opt)
}
func GetQueueInspector() *asynq.Inspector {
opt := RedisURI2AsynqOpt(GetEnv("REDIS_URL"))
opt := RedisURI2AsynqOpt(GetEnv("redis.url"))
return asynq.NewInspector(opt)
}
func RedisURI2AsynqOpt(uri string) asynq.RedisConnOpt {
opt, err := asynq.ParseRedisURI(GetEnv("REDIS_URL"))
opt, err := asynq.ParseRedisURI(GetEnv("redis.url"))
if err != nil {
panic(err)
}

View File

@@ -1,6 +1,8 @@
package utils
import (
"strings"
"github.com/spf13/viper"
)
@@ -15,12 +17,14 @@ func InitEnv() {
return
}
v = viper.New()
v.SetConfigName(".env")
v.SetConfigType("env")
v.SetConfigName("config.yaml")
v.SetConfigType("yaml")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AddConfigPath(".")
v.AddConfigPath("../")
v.AutomaticEnv()
if err := v.ReadInConfig(); err != nil {
err := v.ReadInConfig()
if err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
// 只有当错误不是"配置文件未找到"时才 panic
panic(err)
@@ -40,3 +44,8 @@ func GetEnvWithDefault(key string, defaultValue string) string {
}
return value
}
func GetEnvMapString(key string) map[string]string {
InitEnv()
return v.GetStringMapString(key)
}

View File

@@ -41,7 +41,7 @@ func GetUploadDirPath() (string, error) {
return "", err
}
finalPath := filepath.Join(basepath, "uploads")
uploadPath := GetEnvWithDefault("UPLOAD_PATH", finalPath)
uploadPath := GetEnvWithDefault("upload.path", finalPath)
if err := os.MkdirAll(uploadPath, 0755); err != nil {
return "", err
}

View File

@@ -8,7 +8,7 @@ import (
)
func GeneratePasswordHash(password string) (string, error) {
salt := GetEnv("PASSWORD_SALT")
salt := GetEnv("share.password_salt")
if salt == "" {
return "", errors.New("请配置PASSWORD_SALT")
}

View File

@@ -9,8 +9,8 @@ import (
func TestGeneratePasswordHash(t *testing.T) {
// 保存原始环境变量
originalSalt := os.Getenv("PASSWORD_SALT")
defer os.Setenv("PASSWORD_SALT", originalSalt)
originalSalt := os.Getenv("share.password_salt")
defer os.Setenv("share.password_salt", originalSalt)
tests := []struct {
name string
@@ -20,11 +20,11 @@ func TestGeneratePasswordHash(t *testing.T) {
errorMsg string
}{
{
name: "PASSWORD_SALT未配置",
name: "share.password_salt未配置",
password: "testpassword",
salt: "",
expectError: true,
errorMsg: "请配置PASSWORD_SALT",
errorMsg: "请配置share.password_salt",
},
{
name: "正常生成哈希",
@@ -38,9 +38,9 @@ func TestGeneratePasswordHash(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
// 设置环境变量
if tt.salt != "" {
os.Setenv("PASSWORD_SALT", tt.salt)
os.Setenv("share.password_salt", tt.salt)
} else {
os.Unsetenv("PASSWORD_SALT")
os.Unsetenv("share.password_salt")
}
hash, err := GeneratePasswordHash(tt.password)

View File

@@ -10,7 +10,7 @@ var rdb *redis.Client = InitRedis()
var ctx = context.Background()
func InitRedis() *redis.Client {
opt, err := redis.ParseURL(GetEnv("REDIS_URL"))
opt, err := redis.ParseURL(GetEnv("redis.url"))
if err != nil {
panic(err)
}

View File

@@ -4,6 +4,7 @@ import (
"backend/internal/controllers"
"backend/internal/utils"
"backend/middleware"
"fmt"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
@@ -12,7 +13,7 @@ import (
func main() {
// 日志
var logger *zap.Logger
if utils.GetEnvWithDefault("NODE_ENV", "production") == "production" {
if utils.GetEnvWithDefault("node.env", "production") == "production" {
logger, _ = zap.NewProduction()
} else {
logger, _ = zap.NewDevelopment()
@@ -40,5 +41,5 @@ func main() {
e.GET("/image/compress/:id", controllers.GetCompressImage)
e.GET("/stat", controllers.GetStat)
e.Logger.Fatal(e.Start(":1323"))
e.Logger.Fatal(e.Start(fmt.Sprintf(":%s", utils.GetEnvWithDefault("api.port", "5001"))))
}

View File

@@ -1,23 +1,30 @@
import getApiBaseUrl from '~/lib/getApiBaseUrl'
type UseSeoProps = {
head?: Record<string, any>
seo?: Record<string, any>
}
const useSeo = async (props: UseSeoProps = {}) => {
const { head, seo } = props || {}
const seoMeta = ref<any>()
const seoMeta = ref<{
site_title: string
site_desc: string
site_url: string
site_icon: string
site_bg_url: string
}>()
if (import.meta.server) {
const { SITE_TITLE, SITE_DESC, SITE_URL } = process.env || {}
seoMeta.value = {
site_title: SITE_TITLE,
site_desc: SITE_DESC,
site_url: SITE_URL,
}
await fetch(`${getApiBaseUrl()}/config`)
.then((res) => res.json())
.then(({ data }) => {
seoMeta.value = data
})
const { title } = head || {}
useHead({
link: [
{ rel: 'icon', href: '/logo.png', sizes: 'any' },
{ rel: 'icon', href: seoMeta.value?.site_icon || '/logo.png', sizes: 'any' },
// { rel: 'icon', href: '/favicon.svg', sizes: 'any', type: 'image/svg+xml' },
{ rel: 'apple-touch-icon', sizes: '180x180', href: '/logo.png' },
{ rel: 'apple-touch-icon', sizes: '180x180', href: seoMeta.value?.site_icon || '/logo.png' },
],
meta: [
// used on some mobile browsers
@@ -33,7 +40,7 @@ const useSeo = async (props: UseSeoProps = {}) => {
ogTitle: seoMeta?.value?.site_title,
ogDescription: seoMeta?.value?.site_desc,
ogImage: {
url: `${seoMeta?.value?.site_url}/logo.png`,
url: `${seoMeta?.value?.site_url}${seoMeta?.value?.site_icon || '/logo.png'}`,
width: 1024,
height: 1024,
alt: 'logo',

View File

@@ -0,0 +1,5 @@
const getApiBaseUrl = () => {
return import.meta.env.API_BASE_URL?.replace(/\/$/, '') || 'http://127.0.0.1:5001'
}
export default getApiBaseUrl

View File

@@ -1,4 +1,5 @@
import tailwindcss from '@tailwindcss/vite'
import getApiBaseUrl from './lib/getApiBaseUrl'
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
compatibilityDate: '2024-04-03',
@@ -35,7 +36,7 @@ export default defineNuxtConfig({
nitro: {
routeRules: {
'/api/**': {
proxy: process.env.API_BASE_URL || 'http://127.0.0.1:1323/**',
proxy: `${getApiBaseUrl()}/**`,
},
},
},

View File

@@ -3,7 +3,7 @@ package utils
import "github.com/hibiken/asynq"
func RedisURI2AsynqOpt(uri string) asynq.RedisConnOpt {
opt, err := asynq.ParseRedisURI(GetEnv("REDIS_URL"))
opt, err := asynq.ParseRedisURI(GetEnv("redis.url"))
if err != nil {
panic(err)
}

View File

@@ -1,6 +1,8 @@
package utils
import (
"strings"
"github.com/spf13/viper"
)
@@ -15,12 +17,14 @@ func InitEnv() {
return
}
v = viper.New()
v.SetConfigName(".env")
v.SetConfigType("env")
v.SetConfigName("config.yaml")
v.SetConfigType("yaml")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AddConfigPath(".")
v.AddConfigPath("../")
v.AutomaticEnv()
if err := v.ReadInConfig(); err != nil {
err := v.ReadInConfig()
if err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
// 只有当错误不是"配置文件未找到"时才 panic
panic(err)

View File

@@ -39,7 +39,7 @@ func GetUploadDirPath() (string, error) {
return "", err
}
finalPath := filepath.Join(basepath, "uploads")
uploadPath := GetEnvWithDefault("UPLOAD_PATH", finalPath)
uploadPath := GetEnvWithDefault("upload.path", finalPath)
if err := os.MkdirAll(uploadPath, 0755); err != nil {
return "", err
}

View File

@@ -10,7 +10,7 @@ var rdb *redis.Client = InitRedis()
var ctx = context.Background()
func InitRedis() *redis.Client {
opt, err := redis.ParseURL(GetEnv("REDIS_URL"))
opt, err := redis.ParseURL(GetEnv("redis.url"))
if err != nil {
panic(err)
}

View File

@@ -23,8 +23,8 @@ func main() {
zap.ReplaceGlobals(logger)
srv := asynq.NewServer(
utils.RedisURI2AsynqOpt(utils.GetEnv("REDIS_URL")),
asynq.Config{Concurrency: cast.ToInt(utils.GetEnvWithDefault("WORKER_CONCURRENCY", "4"))},
utils.RedisURI2AsynqOpt(utils.GetEnv("redis.url")),
asynq.Config{Concurrency: cast.ToInt(utils.GetEnvWithDefault("worker.concurrency", "4"))},
)
mux := asynq.NewServeMux()