[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"article-22":3},{"id":4,"title":5,"title_en":6,"abstract":7,"abstract_en":8,"content":9,"content_en":10,"category":11,"banner_id":12,"banner_path":13,"tags":14,"is_recommend":18,"prev_article":19,"next_article":23,"created_at":27},22,"Go 交叉编译缓存导致的诡异 Bug","Weird Bug caused by Go cross-compiled caching","Go 交叉编译缓存导致的诡异 Bug：开发环境正常,生产环境异常","Weird Bug caused by Go cross-compilation caching: The development environment is normal, the production environment is abnormal","# Go 交叉编译缓存导致的诡异 Bug：开发环境正常，生产环境异常\n\n## 问题现象\n\n最近在开发一个 Go 多语言功能时遇到了一个非常诡异的问题：\n\n- **开发环境**：文章列表 API 正常返回英文字段（`title_en`、`abstract_en`）\n- **生产环境**：相同的 API 不返回英文字段，但数据库中字段存在且有数据\n\n这种\"薛定谔的 Bug\"让人抓狂，代码完全一样，为什么会有不同的表现？\n\n## 排查过程\n\n### 第一轮：常规排查\n\n首先怀疑是常见问题：\n\n1. **JSON 标签问题**：检查模型定义，没有 `omitempty` 标签\n2. **数据库查询**：确认生产环境数据库字段存在且有数据\n3. **响应结构体**：确认包含了英文字段\n4. **缓存问题**：怀疑 Redis 缓存，但清除后问题依然存在\n\n### 第二轮：深入分析\n\n查看相关代码逻辑：\n\n```go\n\u002F\u002F 文章创建时异步翻译\ngo func(article models.ArticleModel) {\n    if err := article_ser.ArticleWithTranslate(article.ID, article.Title, article.Abstract, article.Content); err != nil {\n        global.Log.Error(\"文章翻译失败\", zap.Error(err))\n    }\n}(article)\n```\n\n```go\n\u002F\u002F 翻译服务调用腾讯云 API\nfunc ArticleWithTranslate(id uint, title, abstract, content string) error {\n    \u002F\u002F 调用腾讯云翻译 API\n    titleEn, err := translate.TranslateTexts(ctx, title, \"auto\", \"en\", 0)\n    \u002F\u002F ...\n    \u002F\u002F 更新数据库\n    return global.DB.Model(&models.ArticleModel{}).Where(\"id = ?\", id).Updates(map[string]any{\n        \"title_en\":    titleEn,\n        \"abstract_en\": abstractEn,\n        \"content_en\":  contentEn,\n    }).Error\n}\n```\n\n怀疑是翻译服务问题，但生产环境日志中没有翻译失败的错误信息。\n\n### 第三轮：配置和环境\n\n检查了：\n- 配置文件差异\n- 网络访问权限  \n- 腾讯云 API 配置\n- 数据库连接\n\n都没有发现问题。\n\n## 真相大白\n\n最后，抱着试试看的心态，执行了：\n\n```bash\n# 清除 Go 缓存后重新编译\ngo clean -cache -modcache\nGOOS=linux GOARCH=amd64 go build -ldflags=\"-s -w\" -trimpath -o deploy\u002Fxxxxx\n```\n\n**问题神奇地解决了！**\n\n## 原因分析\n\nGo 编译缓存导致的问题，可能的原因：\n\n### 1. 依赖版本不一致\n```go\n\u002F\u002F go.mod 中的版本范围\nrequire github.com\u002Ftencentcloud\u002Ftencentcloud-sdk-go v1.0.x\n```\n\n- 开发时下载了修复 bug 的新版本\n- 交叉编译缓存中是有问题的旧版本\n- 腾讯云 SDK 在某个版本可能有翻译 API 的 bug\n\n### 2. 交叉编译缓存污染\n```bash\n# 可能的执行顺序\nGOOS=linux GOARCH=amd64 go build  # 缓存了有问题的版本\n# 本地修改代码或更新依赖\ngo build                          # 本地正常\nGOOS=linux GOARCH=amd64 go build  # 仍使用旧的交叉编译缓存\n```\n\n### 3. 模块校验和问题\n`go.sum` 文件中的校验和可能不匹配，导致使用了错误版本的依赖。\n\n## 经验总结\n\n### 排查思路\n当遇到\"开发环境正常，生产环境异常\"且找不到明显原因时：\n\n1. 检查常规问题（代码、配置、网络）\n2. 检查应用层缓存（Redis、内存缓存）\n3. **不要忽略编译环节的可能性**\n\n### 预防措施\n\n1. **锁定依赖版本**\n```bash\ngo mod tidy\n```\n\n2. **使用确定的构建脚本**\n```bash\n#!\u002Fbin\u002Fbash\ngo clean -cache -modcache\ngo mod download\nGOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags=\"-s -w\" -trimpath -o deploy\u002Fxxxx\n```\n\n3. **定期清理缓存**\n```bash\n# 在 CI\u002FCD 中加入缓存清理步骤\ngo clean -cache -modcache\n```\n\n### 调试技巧\n\n1. **添加详细日志**\n```go\n\u002F\u002F 在关键路径添加日志\nglobal.Log.Info(\"开始异步翻译\", zap.Uint(\"articleID\", article.ID))\nglobal.Log.Info(\"翻译配置\", zap.String(\"region\", global.Config.Translate.Region))\n```\n\n2. **版本信息记录**\n```go\n\u002F\u002F 在启动时记录依赖版本信息\ngo list -m all\n```\n\n## 结语\n\n这个 bug 的诡异之处在于它完全违背了我们的常识：相同的代码怎么可能有不同的行为？\n\n但现实告诉我们，在复杂的软件系统中，编译缓存、依赖管理、交叉编译等环节都可能成为 bug 的藏身之处。\n\n**记住：当所有常规排查都无果时，不妨试试清除编译缓存。有时候，最简单粗暴的方法反而最有效。**\n\n---\n\n*遇到过类似问题吗？欢迎在评论区分享你的踩坑经历！*","# Strange Bug caused by Go cross-compilation caching: The development environment is normal, the production environment is abnormal\n\n## Problem Phenomenon\n\nRecently, I encountered a very weird problem while developing a Go multi-language feature:\n\n- ** Development environment **: The article list API normally returns English fields (`title_en`,`abstract_en`)\n- ** Production environment **: The same API does not return English fields, but the fields exist and have data in the database\n\nThis kind of \"Schrödinger's Bug\" is crazy. The code is exactly the same. Why does it behave differently?\n\n## Troubleshooting Process\n\n### First round: Regular screening\n\nThe first suspicion is a common problem:\n\n1. **JSON label problem **: Check the model definition, there is no `omitent` label\n2. ** Database query **: Confirm that the production environment database fields exist and have data\n3. ** Response structure **: Confirm that English fields are included\n4. ** Cache problem **: Redis caching is suspected, but the problem still exists after clearing\n\n### Round 2: In-depth analysis\n\nCheck the relevant code logic:\n\n```go\n\u002F\u002FAsynchronous translation when article creation\ngo func(article models.ArticleModel) {\n    if err := article_ser.ArticleWithTranslate(article.ID, article.Title, article.Abstract, article.Content); err != nil {\n        global.Log.Error(\"Article translation failed\", zap.Error(err))\n    }\n}(article)\n```\n\n```go\n\u002F\u002F Translation service calls Tencent Cloud API\nfunc ArticleWithTranslate(id uint, title, abstract, content string) error {\n    \u002F\u002F Call Tencent Cloud Translation API\n    titleEn, err := translate.TranslateTexts(ctx, title, \"auto\", \"en\", 0)\n    \u002F\u002F ...\n    \u002F\u002F Update database\n    return global.DB.Model(&models.ArticleModel{}).Where(\"id = ? \", id).Updates(map[string]any{\n        \"title_en\":    titleEn,\n        \"abstract_en\": abstractEn,\n        \"content_en\":  contentEn,\n    }).Error\n}\n```\n\nIt is suspected that it is a translation service problem, but there is no error message indicating translation failure in the production environment log.\n\n### Round 3: Configuration and Environment\n\nChecked:\n- Configuration file differences\n- network access  \n- Tencent Cloud API configuration\n- database connection\n\nNo problems were found.\n\n### The truth comes out\n\nFinally, with the mentality of giving it a try, I implemented:\n\n```bash\n# Clear Go cache and recompile\ngo clean -cache -modcache\nGOOS=linux GOARCH=amd64 go build -ldflags=\"-s -w\" -trimpath -o deploy\u002Fxxxxx\n```\n\n** The problem was magically solved!**\n\n## Reason analysis\n\nProblems caused by Go compilation caching, possible causes:\n\n### 1. Inconsistent dependent versions\n```go\n\u002F\u002Fversion range in go.mod\nrequire github.com\u002Ftencentcloud\u002Ftencentcloud-sdk-go v1.0.x\n```\n\n- A new version that fixes the bug was downloaded during development\n- There is a problematic older version in the cross-compilation cache\n- Tencent Cloud SDK may have translation API bugs in a certain version\n\n### 2. cross-compilation cache pollution\n```bash\n# Possible execution orders\nGOOS=linux GOARCH= amd64 go build #The problematic version is cached\n# Modify code locally or update dependencies\ngo build                          #Local normal\nGOOS=linux GOARCH= amd64 go build #Still using the old cross-compile cache\n```\n\n### 3. Module checksum issues\nChecksums in the 'go.sum' file may not match, resulting in the use of the wrong version of the dependency.\n\n## Experience summary\n\n### Troubleshooting ideas\nWhen encountering \"the development environment is normal, the production environment is abnormal\" and no obvious reason can be found:\n\n1. Check for general issues (code, configuration, network)\n2. Check application layer cache (Redis, memory cache)\n3. ** Don't ignore the possibility of compilation **\n\n### Preventive measures\n\n1. ** Lock dependent versions **\n```bash\ngo mod tidy\n```\n\n2. ** Use defined build scripts **\n```bash\n#!\u002F bin\u002Fbash\ngo clean -cache -modcache\ngo mod download\nGOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags=\"-s -w\" -trimpath -o deploy\u002Fxxxx\n```\n\n3. ** Clean up cache regularly **\n```bash\n# Add cache cleanup steps to CI\u002FCD\ngo clean -cache -modcache\n```\n\n### Debugging skills\n\n1. ** Add detailed log **\n```go\n\u002F\u002FAdd logs to critical paths\nglobal.Log.Info(\"Start asynchronous translation\", zap.Uint(\"articleID\", article.ID))\nglobal.Log.Info(\"Translation Configuration\", zap.String(\"region\", global.Config.Translate.Region))\n```\n\n2. ** Version information record **\n```go\n\u002F\u002FRecord dependent version information at startup\ngo list -m all\n```\n\n## Conclusion\n\nThe weird thing about this bug is that it completely violates our common sense: how can the same code behave differently?\n\nBut reality tells us that in complex software systems, compilation caching, dependency management, cross-compilation and other aspects may become hiding places for bugs.\n\n** Remember: When all regular troubleshooting fails, try clearing the compilation cache. Sometimes, the simplest and most crude method is the most effective. **\n\n---\n\n* Have you encountered similar problems? Welcome to share your experience of poth-breaking in the comment area!*","部署",0,"https:\u002F\u002Fblog4-1316398321.cos.ap-nanjing.myqcloud.com\u002Fblog5\u002F20250814151835__白雪.png",[15,16,17],"GO","Gin","Linux",false,{"id":20,"title":21,"title_en":22},21,"Vue 3 + Vite 项目中实现 i18n","Implementation of i18n in Vue 3 + Vite project",{"id":24,"title":25,"title_en":26},24,"JWT (JSON Web Token) 技术指南","JWT (JSON Web Token) Technical Guide","2025-08-18T02:24:43+08:00"]