Daily Archives: 20.06.2016
Escape нужных символов в go
Urlencode на go для определённого набора символов https://play.golang.org/p/PmA-XwvFS2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package main import ( "fmt" ) // chars to escape are described in /usr/local/go/src/net/url/url.go:123 which links to RFC 3986 (§3.4); I just removed & and = var charsToEscape = map[rune]bool{ '$': true, '&': false, // it should remain unchanged '+': true, ',': true, '/': true, ':': true, ';': true, '=': false, // it should remain unchanged '?': true, '@': true, } func main() { query := "@a$dsf" fmt.Println(FixURLQuery(query)) } func FixURLQuery(rawURL string) string { fixedURL := make([]byte, len(rawURL) * 3) j := 0 for i := 0; i < len(rawURL); i++ { c :=rawURL[i] if charsToEscape[rune(c)] == true { fixedURL[j] = '%' fixedURL[j+1] = "0123456789ABCDEF"[c>>4] fixedURL[j+2] = "0123456789ABCDEF"[c&15] j += 3 } else { fixedURL[j] = c j++ } } return string(fixedURL[:j]) } |