douzhan6474 2018-04-24 09:14
浏览 52
已采纳

'language.MatchStrings()'返回垃圾

I'm having the following piece of code in go:

var languageMatcher = language.NewMatcher([]language.Tag{
    language.English, // Default if no match
    language.French,
})

lang, _ := r.Cookie("lang")
accept := r.Header.Get("Accept-Language")

var cookieValue = ""

if cookie != nil {
    cookieValue = lang.String()
}

tag, _ := language.MatchStrings(languageMatcher, cookieValue, accept)

log.Debugf(ctx, fmt.Sprintf("Localized %s to %s. cookie: %s | header: %s", path, tag.String(), cookieValue, accept))

http.Redirect(w, r, "/"+tag.String()+path, 302)

Most of it comes from the GoDoc

It's working fine most of the time but sometimes (when browsing in private mode from a computer that never visited the website, or when removing the entire cache from the browser (no lang cookie)); the language.MatchStrings function returns a bunch of garbage in the tag variable like en-u-rg-uszzzz.

Here's the my log.Debugf output:

Localized / to en-u-rg-uszzzz. cookie: | header: en-US,en;q=0.9

Any idea of what is wrong ?

  • 写回答

1条回答 默认 最新

  • dtlab08822 2018-04-24 11:08
    关注

    According to the documentation, the language matcher may add the Unicode extension on the tag:

    The index returned by the Match method corresponds to the index of the matched tag in t, but is augmented with the Unicode extension ('u')of the corresponding preferred tag. This allows user locale options to be passed transparently.

    This explains the weird en-u-rg-uszzzz value. As the matcher provides us the index of the matched language in the array, a workaround would be to use it to retrieve the original language:

    var availableLanguages = []language.Tag{
        language.English, // Default if no match
        language.French,
    }
    var languageMatcher = language.NewMatcher(availableLanguages)
    
    lang, _ := r.Cookie("lang")
    accept := r.Header.Get("Accept-Language")
    
    var cookieValue = ""
    
    if lang != nil { // Be careful: the variable name was wrong
        cookieValue = lang.String()
    }
    
    _, i := language.MatchStrings(languageMatcher, cookieValue, accept)
    
    log.Debugf(ctx, fmt.Sprintf("Localized %s to %s. cookie: %s | header: %s", path, availableLanguages[i].String(), cookieValue, accept))
    
    http.Redirect(w, r, "/"+availableLanguages[i].String()+path, 302)
    

    A bit hacky, but it works.

    Regards!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)