refactor: support i18n
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"cs-agent/internal/pkg/i18nx"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
@@ -11,7 +12,7 @@ import (
|
||||
func GetPathInt64(ctx *gin.Context, name string) (int64, bool) {
|
||||
value, err := strconv.ParseInt(ctx.Param(name), 10, 64)
|
||||
if err != nil {
|
||||
WriteHttpStatusJSON(ctx, http.StatusBadRequest, web.JsonErrorMsg("路径参数错误"))
|
||||
WriteHttpStatusJSON(ctx, http.StatusBadRequest, web.JsonErrorMsg(i18nx.T(ctx, "error.path.invalid", nil)))
|
||||
return 0, false
|
||||
}
|
||||
return value, true
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"cs-agent/internal/pkg/i18nx"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -28,11 +29,19 @@ func PageData(results any, paging *sqls.Paging) any {
|
||||
}
|
||||
|
||||
func WriteJSON(ctx *gin.Context, result any) {
|
||||
ctx.JSON(http.StatusOK, buildJSONResult(result))
|
||||
ctx.JSON(http.StatusOK, localizeJSONResult(ctx, buildJSONResult(result)))
|
||||
}
|
||||
|
||||
func WriteHttpStatusJSON(ctx *gin.Context, statusCode int, result any) {
|
||||
ctx.JSON(statusCode, buildJSONResult(result))
|
||||
ctx.JSON(statusCode, localizeJSONResult(ctx, buildJSONResult(result)))
|
||||
}
|
||||
|
||||
func localizeJSONResult(ctx *gin.Context, result *web.JsonResult) *web.JsonResult {
|
||||
if result == nil || result.Success || result.Message == "" {
|
||||
return result
|
||||
}
|
||||
result.Message = i18nx.TranslateKnownMessage(i18nx.Locale(ctx), result.Message)
|
||||
return result
|
||||
}
|
||||
|
||||
func buildJSONResult(result any) *web.JsonResult {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"cs-agent/internal/pkg/i18nx"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
@@ -67,6 +68,22 @@ func TestWriteJSONWrapsCommonResultTypes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteJSONLocalizesKnownErrorMessages(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
ctx, recorder := testContext()
|
||||
i18nx.SetLocale(ctx, i18nx.LocaleEnUS)
|
||||
|
||||
WriteJSON(ctx, web.JsonErrorMsg("会话不存在"))
|
||||
|
||||
var got web.JsonResult
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if got.Message != "Conversation not found." {
|
||||
t.Fatalf("message = %q, want %q", got.Message, "Conversation not found.")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteHttpStatusJSONUsesProvidedStatus(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
ctx, recorder := testContext()
|
||||
|
||||
Reference in New Issue
Block a user