go实现url编码的解码

2017-11-10  本文已影响525人  大雁儿

go中提供了url方法可以直接实现这个,练习代码中不需要用到一整个url包,所以就提取出来啦

func ishex(c byte) bool {
    switch {
    case '0' <= c && c <= '9':
        return true
    case 'a' <= c && c <= 'f':
        return true
    case 'A' <= c && c <= 'F':
        return true
    }
    return false
}

func unhex(c byte) byte {
    switch {
    case '0' <= c && c <= '9':
        return c - '0'
    case 'a' <= c && c <= 'f':
        return c - 'a' + 10
    case 'A' <= c && c <= 'F':
        return c - 'A' + 10
    }
    return 0
}

func unescape(s string) (string) {
    n := 0
    for i := 0; i < len(s); {
        switch s[i] {
        case '%':
            n++
            if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {
                s = s[i:]
                if len(s) > 3 {
                    s = s[:3]
                }
                return ""
            }
            i += 3
        default:
            i++
        }
    }

    t := make([]byte, len(s)-2*n)
    j := 0
    for i := 0; i < len(s); {
        switch s[i] {
        case '%':
            t[j] = unhex(s[i+1])<<4 | unhex(s[i+2])
            j++
            i += 3
        default:
            t[j] = s[i]
            j++
            i++
        }
    }
    return string(t)
}
上一篇 下一篇

猜你喜欢

热点阅读