Go:官方包 - net 常用方法

参考:Go语言中文网

1、net包

1、lookUp地址信息查找相关

	//InterfaceAddrs 返回该系统的网络接口的地址列表。
	addr, _ := net.InterfaceAddrs()
	fmt.Println(addr)

	//Interfaces 返回该系统的网络接口列表
	interfaces, _ := net.Interfaces()
	fmt.Println(interfaces)

	//LookupAddr 查询某个地址,返回映射到该地址的主机名序列
	lt, _ := net.LookupAddr("www.alibaba.com")
	fmt.Println(lt)

	//LookupCNAME函数查询name的规范DNS名(但该域名未必可以访问)。
	cname, _ := net.LookupCNAME("www.baidu.com")
	fmt.Println(cname)

	//LookupHost函数查询主机的网络地址序列。
	host, _ := net.LookupHost("www.baidu.com")
	fmt.Println(host)

	//LookupIP函数查询主机的ipv4和ipv6地址序列。
	ip, _ := net.LookupIP("www.baidu.com")
	fmt.Println(ip)

2、地址操作

	//函数将host和port合并为一个网络地址。一般格式为"host:port";如果host含有冒号或百分号,格式为"[host]:port"。
	//Ipv6的文字地址或者主机名必须用方括号括起来,如"[::1]:80"、"[ipv6-host]:http"、"[ipv6-host%zone]:80"。
	hp := net.JoinHostPort("127.0.0.1", "8080")
	fmt.Println(hp)

	//函数将格式为"host:port"、"[host]:port"或"[ipv6-host%zone]:port"的网络地址分割为host或ipv6-host%zone和port两个部分。
	shp,port,_ := net.SplitHostPort("127.0.0.1:8080")
	fmt.Println(shp," _ ",port)


3、错误说明

接口定义:

	type Error interface {
	    error
	    Timeout() bool   // 错误是否为超时?
	    Temporary() bool // 错误是否是临时的?
	}

错误说明:

读取主机DNS配置时出现的错误。

	// 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查询的错误。

	// 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
}

地址错误

	type AddrError struct {
		Err  string
		Addr string
	}

返回该错误的操作、网络类型和网络地址。

	// 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、连接(以Tcp为例子)

客户端

	package test

	import (
		"fmt"
		"net"
		"time"
	)
	
	func main() {
		//1.创建链接远程链接服务器,得到一个conn链接
		conn, err := net.Dial("tcp", "127.0.0.1:8081")
		if err != nil {
			fmt.Println("client start err,exit!")
			return
		}
		i := 1
		for {
			//2.调用链接Write写数据
			_, 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)
		}
	}

服务端

	package test

	import (
		"fmt"
		"log"
		"net"
	)
	
	func chkError(err error) {
		if err != nil {
			log.Fatal(err)
		}
	}
	
	func main() {
		//创建一个TCP服务端
		ta, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:8081")
		chkError(err)
		//监听端口
		tl, err2 := net.ListenTCP("tcp", ta)
		chkError(err2)
		fmt.Println("Server Start")
		//.建立链接并处理
		go func() {
			for {
				//如果有客户端链接过来,阻塞会返回
				conn, err := tl.AcceptTCP()
				if err != nil {
					fmt.Println("Accept err", err)
					continue
				}
				//已经与客户端建立链接,处理业务
				go func() {
					for {
						buf := make([]byte, 512)
						cnt, err := conn.Read(buf)
						if err != nil {
							fmt.Println("recv buf err", err)
							continue
						}
						//回显功能
						if _, err := conn.Write(buf[:cnt]); err != nil {
							fmt.Println("write bak buf err", err)
							continue
						}
					}
				}()
			}
		}()
		//阻塞状态
		select {}
	}


2、net/http包

1、连接、监听

	//get方法调用
	resp, err := http.Get("http://example.com/")
	
	//post方法调用
	resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
	
	//表单方式调用
	resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}})
	
	//服务端进行监听端口
	func (srv *Server) ListenAndServe() error 

2、管理HTTP客户端的头域、重定向策略和其他设置

创建Client,发送设置好的request

	client := &http.Client{CheckRedirect: redirectPolicyFunc,}
	resp, err := client.Get("http://example.com")
	req, err := http.NewRequest("GET", "http://example.com", nil)  //创建一个request
	req.Header.Add("If-None-Match", `W/"wyzzy"`) //设置头部
	resp, err := client.Do(req)

3、管理代理、TLS配置、keep-alive、压缩和其他设置

创建一个携带设置好的Transport信息的Client,并进行通信

	tr := &http.Transport{
		TLSClientConfig:    &tls.Config{RootCAs: pool},
		DisableCompression: true,
	}
	client := &http.Client{Transport: tr}
	resp, err := client.Get("https://example.com")

4、完整例子

客户端:

	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))
	}

服务端:

	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"))
	}
发布了117 篇原创文章 · 获赞 15 · 访问量 5613

猜你喜欢

转载自blog.csdn.net/qq_34326321/article/details/104842178