From d8615353ae80b7850354d9acfbd88a04ff5e1328 Mon Sep 17 00:00:00 2001 From: TsMask <340112800@qq.com> Date: Mon, 18 Mar 2024 11:02:21 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20mux=E8=B7=AF=E7=94=B1=E5=B0=81=E8=A3=85?= =?UTF-8?q?=E5=85=BC=E5=AE=B9gin=E7=9A=84ctx=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/core/utils/ctx/ctx.go | 43 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/lib/core/utils/ctx/ctx.go b/lib/core/utils/ctx/ctx.go index 0e30abb4..dfbbe924 100644 --- a/lib/core/utils/ctx/ctx.go +++ b/lib/core/utils/ctx/ctx.go @@ -14,6 +14,7 @@ import ( commonConstants "be.ems/src/framework/constants/common" tokenConst "be.ems/src/framework/constants/token" "github.com/gorilla/mux" + "golang.org/x/text/language" ) // Param 地址栏参数{id} @@ -31,6 +32,11 @@ func GetQuery(r *http.Request, key string) string { return r.URL.Query().Get(key) } +// GetHeader 请求头参数 +func GetHeader(r *http.Request, key string) string { + return r.Header.Get(key) +} + // QueryMap 查询参数转换Map func QueryMap(r *http.Request) map[string]any { queryValues := r.URL.Query() @@ -41,6 +47,16 @@ func QueryMap(r *http.Request) map[string]any { return queryParams } +// ShouldBindQuery 查询参数读取json请求结构团体 +func ShouldBindQuery(r *http.Request, args any) error { + queryParams := QueryMap(r) + body, err := json.Marshal(queryParams) + if err != nil { + return err + } + return json.Unmarshal(body, args) +} + // 读取json请求结构团体 func ShouldBindJSON(r *http.Request, args any) error { body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // 设置较大的长度,例如 1<<20 (1MB) @@ -118,7 +134,32 @@ func Authorization(r *http.Request) string { return arr[1] } -// 定义自定义类型作为键 +// AcceptLanguage 解析客户端接收语言 zh:中文 en: 英文 +func AcceptLanguage(r *http.Request) string { + preferredLanguage := language.English + + // Query请求查询 + if v := GetQuery(r, "language"); v != "" { + tags, _, _ := language.ParseAcceptLanguage(v) + if len(tags) > 0 { + preferredLanguage = tags[0] + } + } + // Header请求头 + if v := GetHeader(r, "Accept-Language"); v != "" { + tags, _, _ := language.ParseAcceptLanguage(v) + if len(tags) > 0 { + preferredLanguage = tags[0] + } + } + + // 只取前缀 + lang := preferredLanguage.String() + arr := strings.Split(lang, "-") + return arr[0] +} + +// ContextKey 定义自定义类型作为键 type ContextKey string // LoginUser 登录用户信息需要Authorize中间件