github.com/zhongdalu/gf@v1.0.0/g/encoding/gurl/url.go (about) 1 // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 7 // Package gurl provides useful API for URL handling. 8 package gurl 9 10 import ( 11 "net/url" 12 "strings" 13 ) 14 15 // url encode string, is + not %20 16 func Encode(str string) string { 17 return url.QueryEscape(str) 18 } 19 20 // url decode string 21 func Decode(str string) (string, error) { 22 return url.QueryUnescape(str) 23 } 24 25 // URL-encode according to RFC 3986. 26 // See http://php.net/manual/en/function.rawurlencode.php. 27 func RawEncode(str string) string { 28 return strings.Replace(url.QueryEscape(str), "+", "%20", -1) 29 } 30 31 // Decode URL-encoded strings. 32 // See http://php.net/manual/en/function.rawurldecode.php. 33 func RawDecode(str string) (string, error) { 34 return url.QueryUnescape(strings.Replace(str, "%20", "+", -1)) 35 } 36 37 // Generate URL-encoded query string. 38 // See http://php.net/manual/en/function.http-build-query.php. 39 func BuildQuery(queryData url.Values) string { 40 return queryData.Encode() 41 } 42 43 // Parse a URL and return its components. 44 // -1: all; 1: scheme; 2: host; 4: port; 8: user; 16: pass; 32: path; 64: query; 128: fragment. 45 // See http://php.net/manual/en/function.parse-url.php. 46 func ParseURL(str string, component int) (map[string]string, error) { 47 u, err := url.Parse(str) 48 if err != nil { 49 return nil, err 50 } 51 if component == -1 { 52 component = 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128 53 } 54 var components = make(map[string]string) 55 if (component & 1) == 1 { 56 components["scheme"] = u.Scheme 57 } 58 if (component & 2) == 2 { 59 components["host"] = u.Hostname() 60 } 61 if (component & 4) == 4 { 62 components["port"] = u.Port() 63 } 64 if (component & 8) == 8 { 65 components["user"] = u.User.Username() 66 } 67 if (component & 16) == 16 { 68 components["pass"], _ = u.User.Password() 69 } 70 if (component & 32) == 32 { 71 components["path"] = u.Path 72 } 73 if (component & 64) == 64 { 74 components["query"] = u.RawQuery 75 } 76 if (component & 128) == 128 { 77 components["fragment"] = u.Fragment 78 } 79 return components, nil 80 }