URL encoding and decoding.

Usage:

  1. import "github.com/gogf/gf/v2/encoding/gurl"

API Documentation:

https://pkg.go.dev/github.com/gogf/gf/v2/encoding/gurl

URL Parameter Construction

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/encoding/gurl"
  5. "net/url"
  6. )
  7. func main() {
  8. // Construct URL parameters
  9. values := url.Values{}
  10. values.Add("name", "gopher")
  11. values.Add("limit", "20")
  12. values.Add("page", "7")
  13. // Generate URL encoded query string limit=20&name=gopher&page=7
  14. urlStr := gurl.BuildQuery(values)
  15. fmt.Println(urlStr)
  16. }

After execution, the output will be:

  1. limit=20&name=gopher&page=7

URL Parameter Encoding and Decoding

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/encoding/gurl"
  5. "log"
  6. )
  7. func main() {
  8. // Encode string for safe placement in URL queries.
  9. encodeStr := gurl.Encode("limit=20&name=gopher&page=7")
  10. fmt.Println(encodeStr)
  11. // Perform URL decoding
  12. decodeStr, err := gurl.Decode("limit%3D20%26name%3Dgopher%26page%3D7")
  13. if err != nil {
  14. log.Fatal(err)
  15. }
  16. fmt.Println(decodeStr)
  17. }

After execution, the output will be:

  1. limit%3D20%26name%3Dgopher%26page%3D7
  2. limit=20&name=gopher&page=7

Parsing URL

component parameter value options:

Parameter ValueDescription
-1all
1scheme
2host
4port
8user
16pass
32path
64query
128fragment
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/encoding/gurl"
  5. "log"
  6. )
  7. func main() {
  8. // Parse URL and return its components
  9. data, err := gurl.ParseURL("http://127.0.0.1:8199/goods?limit=20&name=gopher&page=7", -1)
  10. if err != nil {
  11. log.Fatal(err)
  12. }
  13. fmt.Println(data)
  14. fmt.Println(data["host"])
  15. fmt.Println(data["query"])
  16. fmt.Println(data["path"])
  17. fmt.Println(data["scheme"])
  18. fmt.Println(data["fragment"])
  19. }

After execution, the output will be:

  1. map[fragment: host:127.0.0.1 pass: path:/goods port:8199 query:limit=20&name=gopher&page=7 scheme:http user:]
  2. 127.0.0.1
  3. limit=20&name=gopher&page=7
  4. /goods
  5. http