调整项目结构,factory只负责暴露方法,不实现业务细节

This commit is contained in:
2025-12-07 00:04:01 +08:00
parent b66f345281
commit 339920a940
23 changed files with 2165 additions and 1231 deletions

View File

@@ -1,56 +0,0 @@
package main
import (
"fmt"
"log"
"time"
"git.toowon.com/jimmy/go-common/datetime"
)
func main() {
// 设置默认时区
err := datetime.SetDefaultTimeZone(datetime.AsiaShanghai)
if err != nil {
log.Fatal(err)
}
// 获取当前时间
now := datetime.Now()
fmt.Printf("Current time: %s\n", datetime.FormatDateTime(now))
// 解析时间字符串
t, err := datetime.ParseDateTime("2024-01-01 12:00:00")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Parsed time: %s\n", datetime.FormatDateTime(t))
// 时区转换
t2, err := datetime.ToTimezone(t, datetime.AmericaNewYork)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Time in New York: %s\n", datetime.FormatDateTime(t2))
// Unix时间戳
unix := datetime.ToUnix(now)
fmt.Printf("Unix timestamp: %d\n", unix)
t3 := datetime.FromUnix(unix)
fmt.Printf("From Unix: %s\n", datetime.FormatDateTime(t3))
// 时间计算
tomorrow := datetime.AddDays(now, 1)
fmt.Printf("Tomorrow: %s\n", datetime.FormatDate(tomorrow))
// 时间范围
startOfDay := datetime.StartOfDay(now)
endOfDay := datetime.EndOfDay(now)
fmt.Printf("Start of day: %s\n", datetime.FormatDateTime(startOfDay))
fmt.Printf("End of day: %s\n", datetime.FormatDateTime(endOfDay))
// 时间差
diff := datetime.DiffDays(now, tomorrow)
fmt.Printf("Days difference: %d\n", diff)
}

View File

@@ -1,74 +0,0 @@
package main
import (
"fmt"
"log"
"time"
"git.toowon.com/jimmy/go-common/datetime"
)
func main() {
// 示例1将当前时间转换为UTC
fmt.Println("=== Example 1: Convert Current Time to UTC ===")
now := time.Now()
utcTime := datetime.ToUTC(now)
fmt.Printf("Local time: %s\n", datetime.FormatDateTime(now))
fmt.Printf("UTC time: %s\n", datetime.FormatDateTime(utcTime))
// 示例2从指定时区转换为UTC
fmt.Println("\n=== Example 2: Convert from Specific Timezone to UTC ===")
// 解析上海时区的时间
shanghaiTime, err := datetime.ParseDateTime("2024-01-01 12:00:00", datetime.AsiaShanghai)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Shanghai time: %s\n", datetime.FormatDateTime(shanghaiTime, datetime.AsiaShanghai))
// 转换为UTC
utcTime2, err := datetime.ToUTCFromTimezone(shanghaiTime, datetime.AsiaShanghai)
if err != nil {
log.Fatal(err)
}
fmt.Printf("UTC time: %s\n", datetime.FormatDateTime(utcTime2, datetime.UTC))
// 示例3解析时间字符串并直接转换为UTC
fmt.Println("\n=== Example 3: Parse and Convert to UTC ===")
utcTime3, err := datetime.ParseDateTimeToUTC("2024-01-01 12:00:00", datetime.AsiaShanghai)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Parsed from Shanghai timezone, UTC: %s\n", datetime.FormatDateTime(utcTime3, datetime.UTC))
// 示例4解析日期并转换为UTC
fmt.Println("\n=== Example 4: Parse Date and Convert to UTC ===")
utcTime4, err := datetime.ParseDateToUTC("2024-01-01", datetime.AsiaShanghai)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Date parsed from Shanghai timezone, UTC: %s\n", datetime.FormatDateTime(utcTime4, datetime.UTC))
// 示例5数据库存储场景
fmt.Println("\n=== Example 5: Database Storage Scenario ===")
// 从请求中获取时间(假设是上海时区)
requestTimeStr := "2024-01-01 12:00:00"
requestTimezone := datetime.AsiaShanghai
// 转换为UTC时间用于数据库存储
dbTime, err := datetime.ParseDateTimeToUTC(requestTimeStr, requestTimezone)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Request time (Shanghai): %s\n", requestTimeStr)
fmt.Printf("Database time (UTC): %s\n", datetime.FormatDateTime(dbTime, datetime.UTC))
// 从数据库读取UTC时间转换为用户时区显示
userTimezone := datetime.AsiaShanghai
displayTime, err := datetime.ToTimezone(dbTime, userTimezone)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Display time (Shanghai): %s\n", datetime.FormatDateTime(displayTime, userTimezone))
}

View File

@@ -7,7 +7,6 @@ import (
"time"
"git.toowon.com/jimmy/go-common/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
)
// 示例Factory黑盒模式 - 最简化的使用方式
@@ -44,8 +43,6 @@ func main() {
// 用户列表
func handleUsers(w http.ResponseWriter, r *http.Request) {
h := commonhttp.NewHandler(w, r)
// 创建工厂(在处理器中也可以复用)
fac, _ := factory.NewFactoryFromFile("config.json")
ctx := context.Background()
@@ -59,7 +56,7 @@ func handleUsers(w http.ResponseWriter, r *http.Request) {
cacheKey := "users:list"
cached, _ := fac.RedisGet(ctx, cacheKey)
if cached != "" {
h.Success(cached)
fac.Success(w, cached)
return
}
@@ -72,12 +69,11 @@ func handleUsers(w http.ResponseWriter, r *http.Request) {
// 4. 缓存结果
fac.RedisSet(ctx, cacheKey, users, 5*time.Minute)
h.Success(users)
fac.Success(w, users)
}
// 文件上传
func handleUpload(w http.ResponseWriter, r *http.Request) {
h := commonhttp.NewHandler(w, r)
fac, _ := factory.NewFactoryFromFile("config.json")
ctx := context.Background()
@@ -85,7 +81,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
file, header, err := r.FormFile("file")
if err != nil {
fac.LogError("文件上传失败: %v", err)
h.Error(400, "文件上传失败")
fac.Error(w, 400, "文件上传失败")
return
}
defer file.Close()
@@ -95,7 +91,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
url, err := fac.UploadFile(ctx, objectKey, file, header.Header.Get("Content-Type"))
if err != nil {
fac.LogError("文件上传到存储失败: %v", err)
h.Error(500, "文件上传失败")
fac.Error(w, 500, "文件上传失败")
return
}
@@ -106,7 +102,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
"url": url,
}, "文件上传成功")
h.Success(map[string]interface{}{
fac.Success(w, map[string]interface{}{
"url": url,
})
}
@@ -122,16 +118,14 @@ func authMiddleware(next http.Handler) http.Handler {
// 获取token
token := r.Header.Get("Authorization")
if token == "" {
h := commonhttp.NewHandler(w, r)
h.Error(401, "未授权")
fac.Error(w, 401, "未授权")
return
}
// 从Redis验证token黑盒方法
userID, err := fac.RedisGet(ctx, "token:"+token)
if err != nil || userID == "" {
h := commonhttp.NewHandler(w, r)
h.Error(401, "token无效")
fac.Error(w, 401, "token无效")
return
}

View File

@@ -5,6 +5,7 @@ import (
"net/http"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/factory"
)
// 用户结构
@@ -14,15 +15,17 @@ type User struct {
Email string `json:"email"`
}
// 获取用户列表(使用Handler黑盒模式
func GetUserList(h *commonhttp.Handler) {
// 获取分页参数(简洁方式)
pagination := h.ParsePaginationRequest()
// 获取用户列表(使用公共方法和factory
func GetUserList(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取分页参数(使用公共方法)
pagination := commonhttp.ParsePaginationRequest(r)
page := pagination.GetPage()
pageSize := pagination.GetSize()
// 获取查询参数(简洁方式
_ = h.GetQuery("keyword", "") // 示例:获取查询参数
// 获取查询参数(使用公共方法
_ = commonhttp.GetQuery(r, "keyword", "") // 示例:获取查询参数
// 模拟查询数据
users := []User{
@@ -31,26 +34,28 @@ func GetUserList(h *commonhttp.Handler) {
}
total := int64(100)
// 返回分页响应(简洁方式
h.SuccessPage(users, total, page, pageSize)
// 返回分页响应(使用factory方法
fac.SuccessPage(w, users, total, page, pageSize)
}
// 创建用户(使用Handler黑盒模式
func CreateUser(h *commonhttp.Handler) {
// 解析请求体(简洁方式)
// 创建用户(使用公共方法和factory
func CreateUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 解析请求体(使用公共方法)
var req struct {
Name string `json:"name"`
Email string `json:"email"`
}
if err := h.ParseJSON(&req); err != nil {
h.WriteJSON(http.StatusBadRequest, 400, "请求参数解析失败", nil)
if err := commonhttp.ParseJSON(r, &req); err != nil {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
// 参数验证
if req.Name == "" {
h.Error(1001, "用户名不能为空")
fac.Error(w, 1001, "用户名不能为空")
return
}
@@ -61,49 +66,46 @@ func CreateUser(h *commonhttp.Handler) {
Email: req.Email,
}
// 返回成功响应(简洁方式
h.SuccessWithMessage("创建成功", user)
// 返回成功响应(使用factory方法统一Success方法
fac.Success(w, user, "创建成功")
}
// 获取用户详情(使用Handler黑盒模式
func GetUser(h *commonhttp.Handler) {
// 获取查询参数(简洁方式)
id := h.GetQueryInt64("id", 0)
// 获取用户详情(使用公共方法和factory
func GetUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取查询参数(使用公共方法)
id := commonhttp.GetQueryInt64(r, "id", 0)
if id == 0 {
h.WriteJSON(http.StatusBadRequest, 400, "用户ID不能为空", nil)
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "用户ID不能为空", nil)
return
}
// 模拟查询用户
if id == 1 {
user := User{ID: 1, Name: "User1", Email: "user1@example.com"}
h.Success(user)
fac.Success(w, user)
} else {
h.Error(1002, "用户不存在")
fac.Error(w, 1002, "用户不存在")
}
}
func main() {
// 方式1使用HandleFunc包装器(推荐,最简洁)
http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
switch h.Request().Method {
// 使用标准http.HandleFunc
http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
GetUserList(h)
GetUserList(w, r)
case http.MethodPost:
CreateUser(h)
CreateUser(w, r)
default:
h.WriteJSON(http.StatusMethodNotAllowed, 405, "方法不支持", nil)
commonhttp.WriteJSON(w, http.StatusMethodNotAllowed, 405, "方法不支持", nil)
}
}))
// 方式2手动创建Handler需要更多控制时
http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
h := commonhttp.NewHandler(w, r)
GetUser(h)
})
http.HandleFunc("/user", GetUser)
log.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}

View File

@@ -5,6 +5,7 @@ import (
"net/http"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/factory"
)
// ListUserRequest 用户列表请求(包含分页字段)
@@ -20,21 +21,22 @@ type User struct {
Email string `json:"email"`
}
// 获取用户列表(使用Handler和PaginationRequest
func GetUserList(h *commonhttp.Handler) {
// 获取用户列表(使用公共方法和factory
func GetUserList(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
var req ListUserRequest
// 方式1从JSON请求体解析分页字段会自动解析
if h.Request().Method == http.MethodPost {
if err := h.ParseJSON(&req); err != nil {
h.WriteJSON(http.StatusBadRequest, 400, "请求参数解析失败", nil)
if r.Method == http.MethodPost {
if err := commonhttp.ParseJSON(r, &req); err != nil {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
} else {
// 方式2从查询参数解析分页
pagination := h.ParsePaginationRequest()
pagination := commonhttp.ParsePaginationRequest(r)
req.PaginationRequest = *pagination
req.Keyword = h.GetQuery("keyword", "")
req.Keyword = commonhttp.GetQuery(r, "keyword", "")
}
// 使用分页方法
@@ -49,12 +51,12 @@ func GetUserList(h *commonhttp.Handler) {
}
total := int64(100)
// 返回分页响应
h.SuccessPage(users, total, page, size)
// 返回分页响应使用factory方法
fac.SuccessPage(w, users, total, page, size)
}
func main() {
http.HandleFunc("/users", commonhttp.HandleFunc(GetUserList))
http.HandleFunc("/users", GetUserList)
log.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))

View File

@@ -21,13 +21,11 @@ func main() {
// 定义API处理器
http.Handle("/api/hello", chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) {
h := commonhttp.NewHandler(w, r)
// 获取时区(使用公共方法)
timezone := commonhttp.GetTimezone(r)
// 获取时区
timezone := h.GetTimezone()
// 返回响应
h.Success(map[string]interface{}{
// 返回响应(使用公共方法)
commonhttp.Success(w, map[string]interface{}{
"message": "Hello, World!",
"timezone": timezone,
})