doutouhe5343 2017-04-13 19:44
浏览 40
已采纳

解析字符串和子字符串

I am trying to decode(not validate) a JWT token and read values from its body. And this part of my code also deals with non JWT tokens. So I need to handle both normal tokens (lets say some string) and JWT tokens.

To achieve that, I am splitting token with "." to read JWT body values, but the problem is "index out of range" when I get non JWT tokens(no '.'s)

Go Playground code

package main

import (
    "fmt"
    "strings"
    "encoding/base64"
    "encoding/json"
)

func main() {
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
//nonJwtToken := "xxxxxxx"

    // below line should gracefull throw error if it passed nonJwtToken
    data, err := base64.RawURLEncoding.DecodeString(strings.Trim(strings.Split(token, ".")[1], "."))
    if err !=nil {
        fmt.Printf("error rahu : " , err)

    }

    var result map[string]interface{}
    err = json.Unmarshal(data, &result)
    fmt.Println(result["name"])
    fmt.Println(err)

}

Note that I am not trying to validate JWT, all I am doing is just decoding JWT and reading values from it.

Any suggestions on this would be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • douci1196 2017-04-13 20:01
    关注

    As mentioned in the comment by @RayfenWindspear you should check the length of the slice returned by Split, also you don't need to Trim "." from a string that's the result of a split on "." as the dots are omitted from the result.

    ts := strings.Split(token, ".")
    if len(ts) <= 1 {
        return ErrNonJWTToken
    }
    data, err := base64.RawURLEncoding.DecodeString(ts[1])
    

    https://play.golang.org/p/NPw7dnBTsh

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?