当前位置:网站首页>Common methods of golang net network package
Common methods of golang net network package
2022-07-18 08:31:00 【whatday】
Catalog
1、lookUp Address information search related
4、 Connect ( With Tcp As an example )
2、 management HTTP The header domain of the client 、 Redirection policy and other settings
3、 Management agent 、TLS To configure 、keep-alive、 Compression and other settings
1、net package
1、lookUp Address information search related
//InterfaceAddrs Return the address list of the network interface of the system .
addr, _ := net.InterfaceAddrs()
fmt.Println(addr)
//Interfaces Return the list of network interfaces of the system
interfaces, _ := net.Interfaces()
fmt.Println(interfaces)
//LookupAddr Query an address , Returns the host name sequence mapped to the address
lt, _ := net.LookupAddr("www.alibaba.com")
fmt.Println(lt)
//LookupCNAME Function query name The specification of DNS name ( But the domain name may not be accessible ).
cname, _ := net.LookupCNAME("www.baidu.com")
fmt.Println(cname)
//LookupHost Function to query the network address sequence of the host .
host, _ := net.LookupHost("www.baidu.com")
fmt.Println(host)
//LookupIP Function to query the of the host ipv4 and ipv6 Address sequence .
ip, _ := net.LookupIP("www.baidu.com")
fmt.Println(ip)
2、 Address operation
// Function will host and port Merge into one network address . The general format is "host:port"; If host Contain colon or percent sign , The format is "[host]:port".
//Ipv6 The text address or host name of must be enclosed in square brackets , Such as "[::1]:80"、"[ipv6-host]:http"、"[ipv6-host%zone]:80".
hp := net.JoinHostPort("127.0.0.1", "8080")
fmt.Println(hp)
// The function will be formatted as "host:port"、"[host]:port" or "[ipv6-host%zone]:port" The network address of is divided into host or ipv6-host%zone and port Two parts .
shp,port,_ := net.SplitHostPort("127.0.0.1:8080")
fmt.Println(shp," _ ",port)
3、 Mistakes show
Interface definition :
type Error interface {
error
Timeout() bool // Whether the error is timeout ?
Temporary() bool // Whether the error is temporary ?
}
Mistakes show :
Read host DNS Error in configuration .
// DNSError represents a DNS lookup error.
type DNSError struct {
Err string // description of the error
Name string // name looked for
Server string // server used
IsTimeout bool // if true, timed out; not all timeouts set this
IsTemporary bool // if true, error is temporary; not all errors set this
IsNotFound bool // if true, host could not be found
}
DNS Query error .
// DNSError represents a DNS lookup error.
type DNSError struct {
Err string // description of the error
Name string // name looked for
Server string // server used
IsTimeout bool // if true, timed out; not all timeouts set this
IsTemporary bool // if true, error is temporary; not all errors set this
IsNotFound bool // if true, host could not be found
}
Wrong address
type AddrError struct {
Err string
Addr string
}
Return the operation of this error 、 Network type and network address .
// OpError is the error type usually returned by functions in the net
// package. It describes the operation, network type, and address of
// an error.
type OpError struct
4、 Connect ( With Tcp As an example )
client
package test
import (
"fmt"
"net"
"time"
)
func main() {
//1. Create a linked remote linked server , Get one conn link
conn, err := net.Dial("tcp", "127.0.0.1:8081")
if err != nil {
fmt.Println("client start err,exit!")
return
}
i := 1
for {
//2. Call link Write Writing data
_, err := conn.Write([]byte(fmt.Sprintf("%s:%d", "Hello Server", i)))
if err != nil {
fmt.Println("write conn err", err)
return
}
buf := make([]byte, 512)
cnt, err := conn.Read(buf)
if err != nil {
fmt.Println("read buf err")
return
}
fmt.Printf("Server call back:%s,cnt = %d\n", buf, cnt)
i++
time.Sleep(1)
}
}
Server side
package test
import (
"fmt"
"log"
"net"
)
func chkError(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
// Create a TCP Server side
ta, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:8081")
chkError(err)
// Listening port
tl, err2 := net.ListenTCP("tcp", ta)
chkError(err2)
fmt.Println("Server Start")
//. Establish links and handle
go func() {
for {
// If there is a client link , Blocking will return
conn, err := tl.AcceptTCP()
if err != nil {
fmt.Println("Accept err", err)
continue
}
// A link has been established with the client , Deal with business
go func() {
for {
buf := make([]byte, 512)
cnt, err := conn.Read(buf)
if err != nil {
fmt.Println("recv buf err", err)
continue
}
// Echo function
if _, err := conn.Write(buf[:cnt]); err != nil {
fmt.Println("write bak buf err", err)
continue
}
}
}()
}
}()
// Blocked state
select {}
}
2、net/http package
1、 Connect 、 monitor
//get Method call
resp, err := http.Get("http://example.com/")
//post Method call
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
// Form mode call
resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}})
// The server monitors the port
func (srv *Server) ListenAndServe() error
2、 management HTTP The header domain of the client 、 Redirection policy and other settings
establish Client, Send the set request
client := &http.Client{CheckRedirect: redirectPolicyFunc,}
resp, err := client.Get("http://example.com")
req, err := http.NewRequest("GET", "http://example.com", nil) // Create a request
req.Header.Add("If-None-Match", `W/"wyzzy"`) // Set the head
resp, err := client.Do(req)
3、 Management agent 、TLS To configure 、keep-alive、 Compression and other settings
Create a carry set Transport The information of Client, And communicate
tr := &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: pool},
DisableCompression: true,
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://example.com")
4、 Complete example
client :
package test
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
response, _ := http.Get("http://localhost:80/hello")
defer response.Body.Close()
body, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(body))
}
Server side :
package test
import (
"flag"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
host := flag.String("host", "127.0.0.1", "listen host")
port := flag.String("port", "80", "listen port")
http.HandleFunc("/hello", Hello)
err := http.ListenAndServe(*host+":"+*port, nil)
if err != nil {
panic(err)
}
}
func Hello(w http.ResponseWriter, req *http.Request) {
_, _ = w.Write([]byte("Hello World"))
}
边栏推荐
- @Repository @ [email protected] Understanding of annotations
- One question per day · 1252 Number of odd cells · simulation optimization
- Face beating
- STL值string学习
- EasyGBS平台编辑设备管理分组时,出现崩溃该如何解决?
- Des dizaines de milliards de données compressées à 600 go, tdengine est installé sur la plateforme mobile d'énergie de GCL
- Signification physique de la transformation de Fourier
- One question per day · 735 Planetary collision · stack simulation
- (zero six) flask is OK if you have hands - configure static files
- 薄膜铜箔导电电位测量
猜你喜欢

Torch in pytoch repeat_ Analysis of interleave() function

Anhui University store

Qt(六)数值与字符串转换

安徽大学店铺

Des dizaines de milliards de données compressées à 600 go, tdengine est installé sur la plateforme mobile d'énergie de GCL
![[untitled] slow SQL analysis and optimization](/img/0c/24200bc7052e87ae4d93b309b12c5d.png)
[untitled] slow SQL analysis and optimization

clickhouse 20.x 分布式表测试与chproxy的部署(二)

Software architecture and design (VIII) -- distributed architecture

338. Bit counting · dynamic programming

5 practices of ITSM to ensure the agility of IT service desk
随机推荐
clickhouse 20.x 分布式表测试与chproxy的部署(二)
umask计算创建文件、目录的默认权限
8254 timer / counter application experiment
Matlab: exchange two rows (columns) of the matrix
C# Channel 简单实现消息队列的发布、订阅
Is it true or false that blue collar workers are sleepy and live broadcasting is needed?
Openpyxl drawing pie chart
Provide/Inject
Torch in pytoch Max() function analysis
Solutions to SSL and time zone errors when using JDBC to operate the database
Software architecture and design (VI) -- hierarchy
华为通用卡证识别功能,一键实现多种卡绑定
Matlab: usage of split dataset spliteachlabel()
golang net 网络包 常用方法
Is it safe for tongdaxin to open an account? Which securities are good for opening an account
Software architecture and design (VIII) -- distributed architecture
Matlab: usage of reading imagedatastore() from dataset
mysql 报错 mysqld:sort aborted:Server shutdown in progress 原因
Matlab: usage of image enhancement imagedataaugmenter()
Qt(十三)QChart绘制折线图