1. Socket Programming
When writing network programs in Go, we will not see the traditional encoding. In the past, when we used Socket to program, we would follow the steps below to expand.
Create Socket: Usesocket()
function.
Bound Socket: Usebind()
function.
Listening: Uselisten()
function. Or connect: Useconnect()
function.
Accept connection: Useaccept()
function.
Receive: Usereceive()
function. Or send: Usesend()
function.
The Go language standard library abstracts and encapsulates this process. No matter what protocol we expect to use to establish a connection, we only need to call it()
Just do it.
1.1 Dial() function
The prototype of the Dial() function is as follows:
func Dial(net, addr string) (Conn, error)
innet
The parameter is the name of the network protocol.addr
The parameters areIP
The address or domain name, and the port number is:
The form is followed by the address or domain name, with the port number optional. If the connection is successful, return the connection object, otherwise returnerror
。
Let's take a look at several common protocol calls.
TCP
Link:
conn, err := ("tcp", "192.168.1.8:3000")
UDP
Link:
conn, err := ("udp", "192.168.1.12:975")
ICMP
Link (using the protocol name):
conn, err := ("ip4:icmp", "")
ICMP
Link (using protocol number):
conn, err := ("ip4:1", "10.0.0.3")
After successfully establishing the connection, we can send and receive data. When sending data, useconn
ofWrite()
Member method, used when receiving dataRead()
method.
2. HTTP Programming
2.1 HTTP Client
Go built-innet/http
The package provides the simplestHTTP
Client implementation, we do not need to use third-party network communication libraries (e.g.libcurl
) You can use the most used HTTP directlyGET
andPOST
Request data in a way.
Basic Methods
net/http
PackedClient
Types provide the following methods, allowing us to implement them in the simplest wayHTTP
ask:
func (c *Client) Get(url string) (r *Response, err error) func (c *Client) Post(url string, bodyType string, body ) (r *Response, err error) func (c *Client) PostForm(url string, data ) (r *Response, err error) func (c *Client) Head(url string) (r *Response, err error) func (c *Client) Do(req *Request) (resp *Response, err error)
The following is a brief introduction to these methods.
- ()
To request a resource, just call the () method (equivalent to ()). The sample code is as follows:
resp, err := ("/") if err != nil { // Handle errors... return } defer () (, )
The above code requests a website homepage and prints its web page content into the standard output stream.
- ()
ToPOST
Sending data in a way is also very simple, just call()
Method and pass the following 3 parameters in turn:
The requested target URL will POST data bitstream ([]byte form) of the resource type (MIMEType) data
The following sample code demonstrates how to upload an image:
resp, err := ("/upload", "image/jpeg", &imageDataBuf) if err != nil{ // Handle errors return } if != {// Handle errors return }
- ()
()
The method implements the standard encoding format asapplication/x-www-form-urlencoded
form submission. The following sample code simulates submitting a new article in an HTML form:
resp, err := ("/posts", {"title": {"article title"}, "content": {"article body"}}) if err != nil{ // Handle errors return }
- ()
The head request method in HTTP indicates that only the header information of the target URL is requested, that is, the HTTP Header is not returned.
Body. Go built-innet/http
The package is also provided()
Method, the same method()
The same method,
Just pass in the target URL one parameter. The following sample code requests HTTP Header information on the homepage of a website:
resp, err := ("/")
- (*).Do()
In most cases,()
and()
It can meet the needs, but if we initiate
HTTP requests require more custom information. We hope to set some custom Http Header fields, such as:
- Set a custom "User-Agent"
- Delivery Cookies
Can be used at this timenet/http
BagThe object's
Do()
Method to implement
req, err := ("GET", "", nil) // ... ("User-Agent", "Gobook Custom User-Agent") // ... client := &{ //... } resp, err := (req)
2.2 HTTP server
2.2.1 Handling HTTP requests
usenet/http
Package provided()
Method, you can listen at the specified address and enable HTTP. The prototype of this method on the server is as follows:
func ListenAndServe(addr string, handler Handler) error
This method is used in the specifiedTCP
Network addressaddr
Listen and call the server handler to handle the incoming connection request. This method has two parameters: the first parameteraddr
That is, the listening address; the second parameter represents the server handler, which is usually empty, which means that the server callsProcessing, and the business logic handler written by the server
()
or()
Default injectionThe specific code is as follows:
("/foo", fooHandler) ("/bar", func(w , r *) { (w, "Hello, %q", ()) }) ((":8080", nil))
net/http
Package also provided()
Method for processingHTTPS
Connection request:
func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error
ListenAndServeTLS()
andListenAndServe()
The behavior is consistent, the difference is that it only handlesHTTPS
ask. In addition, there must be a related file on the server that contains the certificate and the matching private key, such ascertFile
correspondSSL certificate
File storage path,keyFile
Corresponding to the certificate private key file path. If the certificate is signed by the certificate authority,certFile
The path specified by the parameter must be stored on the server viaCA
CertifiedSSL Certificate
。
3. RPC programming
In Go, the net/rpc package provided by the standard library implements the relevant details required by the RPC protocol, and developers can easily use this package to write RPC server and client programs, which makes communication between multiple processes developed in the Go language very simple.
net/rpc
Package allowedRPC
The client program calls a public method of a remote object through a network or other I/O connection (must start with capital letters and be called externally). On the RPC server, an object can be registered as an accessible service, and the object's public method can then provide access in a remote manner. A RPC server can register multiple objects of different types, but does not allow multiple objects of the same type to be registered.
Only methods in an object that meet the following conditions can be set to be remotely accessible by the RPC server:
- Must be a method that can be publicly called outside the object (capitalize);
- There must be two parameters, and the types of the parameters must be types that can be accessed outside the package or types supported by Go in built-in;
- The second parameter must be a pointer;
- The method must return a value of type error.
The above 4 conditions can be simply expressed in the following line of code:
func (t *T) MethodName(argType T1, replyType *T2) error
In the above line of code, types T, T1 and T2 will use Go built-in by defaultencoding/gob
The package is encoded and decoded.
The first parameter of this method (MethodName) is represented byRPC
The parameter passed by the client, the second parameter indicates that it is to be returned toRPC
The result of the client, the method finally returns aerror
Value of type.RPC
The server can call itProcess a single connection request. In most cases,
TCP
OrHTTP
It is a good choice to listen on a network address to create the service.
3.1 RPC support and processing in Go language
In Go, the standard library providesnet/rpc
The package has been implementedRPC
The relevant details required by the protocol can be easily used by developers to write RPC's server and client programs, which makes communication between multiple processes developed in the Go language very simple.
net/rpc
Package allowedRPC
The client program calls a public method of a remote object through a network or other I/O connection (must start with capital letters and be called externally). existRPC
The server can register an object as an accessible service, and then the public method of the object can provide access in a remote manner. oneRPC
The server can register multiple objects of different types, but it is not allowed to register multiple objects of the same type.
Only methods that meet the following conditions can beRPC
The server is set to be remotely accessible:
- Must be a method that can be publicly called outside the object (capitalize);
- There must be two parameters, and the types of the parameters must be of type that can be accessed outside the package or
Go
Built-in supported types; - The second parameter must be a pointer;
- The method must return a value of type error.
The above 4 conditions can be simply expressed in the following line of code:
func (t *T) MethodName(argType T1, replyType *T2) error
In the above line of code, types T, T1 and T2 will use Go built-in by defaultencoding/gob
The package is encoded and decoded. aboutencoding/gob
We will introduce the contents of the package later.
The first parameter of this method (MethodName) represents the parameter passed in by the RPC client, and the second parameter represents the return toRPC
The result of the client, the method finally returns a value of type error.
RPC
The server can call itProcess a single connection request. In most cases,
TCP
OrHTTP
It is a good choice to listen on a network address to create the service.
3.2 Introduction to Gob
Gob
It is a coded and decoding tool for serializing data structures in Go.Go
Built-in in the standard libraryencoding/gob
Package for use. A data structure to useGob
After serialization, it can be used for network transmission.
andJSON
orXML
This data exchange language based on text description is different,Gob
is a binary encoded data stream, andGob
Flow is self-explanatory. While ensuring high efficiency, it also has complete expression capabilities.
As a targetGo
The dedicated serialization method for encoding and decoding of data structures meansGob
Cannot be used across languages. existGo
ofnet/rpc
In the package, the encoding and decoder required to transmit data is the defaultGob
. becauseGob
Limited to useGo
Language development programs, which means we can only useGo
ofRPC
Implement inter-process communication.
However, most of the time, we useGo
WrittenRPC
The server (or client), may prefer it to be universal and language-independent, whether implemented in Python, Java, or other programming languagesRPC
Clients can communicate with it.
3.3 Design an elegant RPC interface
Go'snet/rpc
Very flexible, it implements the interface definition of the encoding and decoder before and after data transmission. This means that developers can customize the way data is transmitted and the interaction between the RPC server and the client.RPC
The provided encoding and decoder interface is as follows:
type ClientCodec interface { WriteRequest(*Request, interface{}) error ReadResponseHeader(*Response) error ReadResponseBody(interface{}) error Close() error } type ServerCodec interface { ReadRequestHeader(*Request) error ReadRequestBody(interface{}) error WriteResponse(*Response, interface{}) error Close() error }
interfaceClientCodec
DefinedRPC
How to get a client in oneRPC
Send requests and read responses in a session. Client program passesWriteRequest()
Method writes a request to the RPC connection and passesReadResponseHeader()
andReadResponseBody()
Read the server response information. After the entire process is completed, passClose()
method to close the connection.
interfaceServerCodec
DefinedRPC
How to be in a serverRPC
Receive requests and send responses in the session. The server program passesReadRequestHeader()
andReadRequestBody()
The method reads the request information from an RPC connection and then sends a response to the RPC client in the connection through the WriteResponse() method. When the process is completed,Close()
Method to close the connection.
By implementing the above interface, we can customize the encoding and decoding methods before and after data transmission, not only toGob
. Similarly, customizableRPC
Interaction between the server and the client. In fact,Go
Provided by the standard librarynet/rpc/json
Package is achieved in one setand
Interface
JSON-RPC
Module.
The above is the detailed content of the seven introductory tutorials in Go language, six network programming. For more information about Go language network programming, please pay attention to my other related articles!
How to learn Go
If you are a novice, you can learn Go language like this~
Seven Introduction Go Language
Article 1:A first look at Go introduction
Article 2:Introduction to program structure & data types
Article 3:Introduction to function method interface
Chapter 4:Concurrent programming of channels and Goroutine
Chapter 5:Operation and processing of files and packages
Chapter 7:GC Garbage Recycling Three-Color Mark