解析字符串和子字符串

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.

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