douci2015 2018-12-19 22:21
浏览 351
已采纳

无法将nil转换为字符串类型

I have this piece of code in a middleware func:

params := r.URL.Query()

tok := params["x-huru-api-token"][0];

if tok == nil {
    tok := r.Header.Get("x-huru-api-token")
}

but I get this error:

enter image description here

anybody know what that's about?

  • 写回答

2条回答 默认 最新

  • dream8877 2018-12-19 23:42
    关注

    The value nil is not a valid value for a string. If you want to fallback to the header on both missing values and empty values, then using the following code:

    params := r.URL.Query()
    tok := params.Get("x-huru-api-token")
    if tok == "" {
        tok = r.Header.Get("x-huru-api-token")
    }
    

    If you only want to fallback to the header when the query parameter is missing, then use the following:

    params := r.URL.Query()
    var tok string
    if values, ok := params["x-huru-api-token"]; ok && len(values) > 0 {
       tok = values[0]  // note that tok can be the empty string ""
    } else {
       tok = r.Header.Get("x-huru-api-token")
    }
    

    Note one difference between the code in this answer and the question. This answer uses assignment to set tok inside the if statement. The code in the question uses a short variable declaration. The short variable declaration will not compile because the newly declared variable inside the if statement is not used.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条