Home Swift UNIX C Assembly Go Web MCU Research Non-Tech

How to use Go to get URL parses, and problems when using it

2023-08-13 | Go | #Words: 476 | 中文原版

Using Go to get URL parses is easy, but Go has strict package manage. So recommend you use goimports tools or shortcut key “Command + S” to auto complete the package. Because now use "net/url" or "net/http", but in future maybe change.

Example URL is https://www.example.com/?keyword=abc&id=12.

Next, url.Parse() will parse the above URL and set error information. Finally, declare the variable q to obtain the parses:

u, err := url.Parse("https://www.example.com/?keyword=abc&id=12")
if err != nil {
	log.Fatal(err)
}
q := u.Query()

u.Query() mapped parse names and values. Since there may be multiple identical parse names, the values here is a string array. You can get the parses through q:

fmt.Println(q["keyword"])
fmt.Println(q["id"])

Output:

[abc]
[12]

Let me explain some troubles when you use it.

How to convert parse string to integer

The q["keyword"] or q["id"] here is actually a string array, so if you want to convert the value 12 of id to integer, you have to use the following method (if you have multiple id parses, choose which you want):

id := strconv.Atoi(q["id"][0])

Now, the id value is the integer 12.

Determine whether there are parses or a specfied parse

Generally, parses are used for calculation or judgment, but what if we want to judge whether there is a parse part or whether there is a specfied parse?

There are two options:

The first method is check whether q or a specfied parse is empty, as follows:

// check whether have parse
if q != nil {
	...
}
// check whether have parse `id`
if q["id"] != nil {
	...
}

The second method is that check the length of q or some parses by len():

// check whether have parse
if len(q) != 0 {
	...
}
// check whether have parse `id`
if len(q["id"]) != 0 {
	...
}

I hope these will help someone in need~