In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the Go language net and url package how to use the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this Go language net and url package how to use the article will have a harvest, let's take a look.
Introduction
In Golang, it is important to package URL to get data from the server. All you need to know is whether you are working on any application and you want to get data for this application from any external location or server, we need to be able to use URL.
URL format
URL contains various parameters: for example, port, search string in URL, and so on. URL can contain various methods that allow it to handle URL properties and make modifications. For example, if we have a similar URL www.exmple.com:3000, 3000 is the port of URL, we can access the port number with the wrapper function in net/url, and in the same way, we can also check whether the URL format is valid.
Let's first take a look at the common URL formats:
: /: @: /? #
Scheme: how the scenario accesses the primary identifier of the specified resource, which tells the URL application which protocol should be used to parse it
User: user name
Password: password
Host: the host component identifies the host machine on the Internet that can access resources, which can be represented by a hostname or an IP address
Port: the port identifies the network port that the server is listening on. The default port number is 80
Path: the path component of URL shows where the resource is located on the server
Params: URL accesses resources through protocol parameters, lists of name-value pairs, and semicolon segmentation
Query: a string narrows the scope of the requested resource class by asking questions or making queries
Frag: to refer to a part of a resource or a fragment of a resource, such as URL to specify a picture or a section in an HTML document
HTTP usually only deals with the entire object, not fragments of the object, and the client cannot pass the fragment to the server. After the browser gets the entire resource from the server, it will display the part of the fragment that you are interested in according to the fragment.
Corresponding to the structure of URL in Go:
Type URL struct {Scheme string Opaque string / / encoded opaque data User * Userinfo / / username and password information Host string / / host or host:port Path string / / path (relative paths may omit leading slash) RawPath string / / encoded path hint (see EscapedPath method) ForceQuery bool / / append a query (?') Even if RawQuery is empty RawQuery string / / encoded query values, without'?' Fragment string / / fragment for references, without'# 'RawFragment string / / encoded fragment hint (see EscapedFragment method)} Go url package function uses format
Go's net/url provides a number of built-in functions for handling URL, which are used in the following format:
URL, error: = url.inbuilt-function-name ("url")
URL: this contains some basic details of the URL name and URL. We can give it any name. It's like any variable.
Error: this is the error part in case of a URL error or any exception, in which case the URL will return an error and the error will be caught in the error section.
Inbuilt-function-name: as we discussed, there are many functions in the URL package that can handle URL, such as Parse, Path, Rawpath, string (), all of which we can use for different purposes.
How to use the URL package
Before we can understand how the url package works, we need to understand the basic usage. When we click on any url, it can contain many properties, such as it can have some ports, it can have some searches, it can have some paths, etc., so we use URL to manipulate and handle all of these things. Let's look at how the URL package works in the go language.
Package mainimport ("fmt"log"net/url") func TestURL () {URL, err: = url.Parse ("https://www.baidu.com/s?wd=golang")fmt.Println("Url before modification is", URL) if err! = nil {log.Fatal ("An error occurs while handling url", err)} URL.Scheme = "https" URL.Host = "bing.com" query: = URL.Query () query.Set ("Q" "go" URL.RawQuery = query.Encode () fmt.Println ("The url after modification is", URL)} func main () {TestURL ()}
Running result:
$go run main.go
Url before modification is https://www.baidu.com/s?wd=golang
The url after modification is https://bing.com/s?q=go&wd=golang
URL Encoding query string in Golang
Go's net/url package contains a built-in method called QueryEscape that escapes / encodes strings so that they can be safely placed in URL queries. The following example shows how to encode a query string in Golang:
Package mainimport ("fmt"net/url") func main () {query: = "Hello World" fmt.Println (url.QueryEscape (query))}
Running result:
$go run main.go
Hello+World
URL coding of multiple query parameters in Golang
If you want to encode more than one query parameter at a time, you can create a url.Values structure that contains the mapping of query parameters to values, and use the url.Values.Encode () method to encode all query parameters.
Package mainimport ("fmt"net/url") func main () {params: = url.Values {} params.Add ("name", "@ Wade") params.Add ("phone", "+ 111111111111") fmt.Println (params.Encode ())}
Run the code:
$go run main.go
Name=%40Wade&phone=%2B111111111111
URL coding of path segments in Golang
Just like QueryEscape, the net/url package in Go has another function called PathEscape () to encode the string so that it can be safely placed in the path segment of the URL:
Package mainimport ("fmt"net/url") func main () {path: = "path with?reserved+characters" fmt.Println (url.PathEscape (path))}
Running result:
$go run main.go
Path%20with%3Freserved+characters
Build a complete URL by coding each part
Finally, let's look at a complete example of URL parsing and URL coding in Golang:
Package mainimport ("fmt"net/url") func main () {/ / Let's start with a base urlbaseUrl, err: = url.Parse ("http://www.bing.com")if err! = nil {fmt.Println (" Malformed URL: ", err.Error ()) return} / / Add a Path Segment (Path segment is automatically escaped) baseUrl.Path + =" path with?reserved characters "/ / Prepare Query Parametersparams: = url.Values {} params.Add (" Q "," Hello World ") params.Add (" u " "@ wade") / / Add Query Parameters to the URLbaseUrl.RawQuery = params.Encode () / / Escape Query Parametersfmt.Printf ("Encoded URL is% Q\ n", baseUrl.String ())}
Run the code:
$go run main.go
Encoded URL is "http://www.bing.com/path%20with%3Freserved%20characters?q=Hello+World&u=%40wade"
Parse URLpackage mainimport ("fmt"log"net/url") func TestURL () {URL, err: = url.Parse ("http://bing.com/good%2bad")fmt.Println("Url before modification is", URL) if err! = nil {log.Fatal ("An error occurs while handling url", err)} fmt.Println ("The URL path is", URL.Path) fmt.Println ("The URL raw path is", URL.RawPath) fmt.Println ("The URL is") in Golang URL.String ()} func main () {TestURL ()}
Run the code:
$go run main.go
Url before modification is http://bing.com/good%2bad
The URL path is / good+ad
The URL raw path is / good%2bad
The URL is http://bing.com/good%2bad
Handle the relative path package mainimport ("fmt"log"net/url") func ExampleURL () {URL, error: = url.Parse (".. / / search?q=php") fmt.Println ("Url before modification is", URL) if error! = nil {log.Fatal ("An error occurs while handling url", error)} baseURL, err: = url.Parse ("http://example.com/directory/")if err! = nil {log.Fatal (" An error occurs while handling url ") Err)} fmt.Println (baseURL.ResolveReference (URL))} func main () {ExampleURL ()}
$go run main.go
Url before modification is.. / / search?q=php
Http://example.com/search?q=php
Parse the space package mainimport ("fmt"log"net/url") func ExampleURL () {URL, error: = url.Parse ("http://example.com/Here path with space") if error! = nil {log.Fatal ("An error occurs while handling url", error)} fmt.Println ("The Url is", URL)} func main () {ExampleURL ()}
Running result:
$go run main.go
The Url is http://example.com/Here%20path%20with%20space
Judge the absolute address package mainimport ("fmt"net/url") func main () {u: = url.URL {Host: "example.com", Path: "foo"} fmt.Println ("The Url is", u.IsAbs ()) u.Scheme = "http" fmt.Println ("The Url is", u.IsAbs ())}
$go run main.go
The Url is false
The Url is true
Parse port package mainimport ("fmt"log"net/url") func ExampleURL () {URL1, error: = url.Parse ("https://example.org")fmt.Println("URL1 before modification is", URL1) if error! = nil {log.Fatal ("An error occurs while handling url", error)} URL2, err: = url.Parse ("https://example.org:8080")if err! = nil {log.Fatal (" An error occurs while handling url ") URL2)} fmt.Println ("URL2 before modification is" URL2) fmt.Println ("URL2 Port number is", URL2.Port ())} func main () {ExampleURL ()}
$go run main.go
URL1 before modification is https://example.org
URL2 before modification is https://example.org:8080
URL2 Port number is 8080
This is the end of the article on "how to use net and url packages in Go". Thank you for reading! I believe you all have a certain understanding of "how to use net and url packages in Go". If you want to learn more, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.