SoFunction
Updated on 2025-03-03

Seven introductory tutorials for Go language six network programming

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)

innetThe parameter is the name of the network protocol.addrThe 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.

TCPLink:

conn, err := ("tcp", "192.168.1.8:3000")

UDPLink:

conn, err := ("udp", "192.168.1.12:975")

ICMPLink (using the protocol name):

conn, err := ("ip4:icmp", "")

ICMPLink (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, useconnofWrite()Member method, used when receiving dataRead()method.

2. HTTP Programming

2.1 HTTP Client

Go built-innet/httpThe package provides the simplestHTTPClient implementation, we do not need to use third-party network communication libraries (e.g.libcurl) You can use the most used HTTP directlyGETandPOSTRequest data in a way.

Basic Methods

net/httpPackedClientTypes provide the following methods, allowing us to implement them in the simplest wayHTTPask:

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.

  • ()

ToPOSTSending 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-urlencodedform 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/httpThe 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/httpBagThe object'sDo()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/httpPackage 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 specifiedTCPNetwork addressaddrListen and call the server handler to handle the incoming connection request. This method has two parameters: the first parameteraddrThat 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/httpPackage also provided()Method for processingHTTPSConnection request:

func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error

ListenAndServeTLS()andListenAndServe()The behavior is consistent, the difference is that it only handlesHTTPSask. In addition, there must be a related file on the server that contains the certificate and the matching private key, such ascertFilecorrespondSSL certificateFile storage path,keyFileCorresponding to the certificate private key file path. If the certificate is signed by the certificate authority,certFileThe path specified by the parameter must be stored on the server viaCACertifiedSSL 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/rpcPackage allowedRPCThe 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/gobThe package is encoded and decoded.

The first parameter of this method (MethodName) is represented byRPCThe parameter passed by the client, the second parameter indicates that it is to be returned toRPCThe result of the client, the method finally returns aerrorValue of type.
RPCThe server can call itProcess a single connection request. In most cases,TCPOrHTTPIt 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/rpcThe package has been implementedRPCThe 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/rpcPackage allowedRPCThe 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). existRPCThe server can register an object as an accessible service, and then the public method of the object can provide access in a remote manner. oneRPCThe 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 beRPCThe 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 orGoBuilt-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/gobThe package is encoded and decoded. aboutencoding/gobWe 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 toRPCThe result of the client, the method finally returns a value of type error.

RPCThe server can call itProcess a single connection request. In most cases,TCPOrHTTPIt is a good choice to listen on a network address to create the service.

3.2 Introduction to Gob

GobIt is a coded and decoding tool for serializing data structures in Go.GoBuilt-in in the standard libraryencoding/gobPackage for use. A data structure to useGobAfter serialization, it can be used for network transmission.

andJSONorXMLThis data exchange language based on text description is different,Gobis a binary encoded data stream, andGobFlow is self-explanatory. While ensuring high efficiency, it also has complete expression capabilities.

As a targetGoThe dedicated serialization method for encoding and decoding of data structures meansGobCannot be used across languages. existGoofnet/rpcIn the package, the encoding and decoder required to transmit data is the defaultGob. becauseGobLimited to useGoLanguage development programs, which means we can only useGoofRPCImplement inter-process communication.

However, most of the time, we useGoWrittenRPCThe server (or client), may prefer it to be universal and language-independent, whether implemented in Python, Java, or other programming languagesRPCClients can communicate with it.

3.3 Design an elegant RPC interface

Go'snet/rpcVery 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.
RPCThe 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
}

interfaceClientCodecDefinedRPCHow to get a client in oneRPCSend 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.

interfaceServerCodecDefinedRPCHow to be in a serverRPCReceive 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, customizableRPCInteraction between the server and the client. In fact,GoProvided by the standard librarynet/rpc/jsonPackage is achieved in one setandInterfaceJSON-RPCModule.

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