Go-http基本应用

郤坚诚
2023-12-01

http

获取http请求服务器

package main

import (
	"fmt"
	"net"
)

func main() {
	listener, err := net.Listen("tcp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("net.Listen err")
		return
	}
	defer listener.Close()  //延迟关闭

	conn, err := listener.Accept()
	if err != nil {
		fmt.Println("Accpet err:")
	}
	defer conn.Close()

	//缓冲区
	buf := make([]byte, 2048)
	n, err := conn.Read(buf)
	if n==0{
		return
	}
	if err != nil {
		fmt.Println("conn.Read err")

	}

	fmt.Println(string(buf[:n]))

	//结果
	//GET / HTTP/1.1
	//Host: 127.0.0.1:8000
	//Connection: keep-alive
	//Upgrade-Insecure-Requests: 1
	//User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36
	//Sec-Fetch-Mode: navigate
	//Sec-Fetch-User: ?1
	//Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
	//Sec-Fetch-Site: none
	//Accept-Encoding: gzip, deflate, br
	//Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
}

http-测试服务器端

package main

import (
	"net/http
)

func main(){
	//注册回调函数。该回调函数会在服务器被访问时,自动被调用。
	http.HandleFunc("/hello",hello)
	//绑定服务器监听地址
	http.ListenAndServe("127.0.0.1",nil)
}

func hello(w http.ResponseWriter, r *http.Request){
	//w: 写回客户端浏览器的数据
	//r: 读取客户端浏览器的数据
	w.Write([]byte("hello world"))
}

http-测试客户端


package main

import (
	"fmt"
	"net"
)

const IP  = "127.0.0.1:8000"
func main() {
	conn, err := net.Dial("tcp", IP)
	if err != nil {
		fmt.Println("deDial",err)
		return
	}
	defer conn.Close()

	httpRequest := "GET /hello HTTP/1.1\r\nHost:127.0.0.1:8000\r\n\r\n"

	_, _ = conn.Write([]byte(httpRequest))
	buffer := make([]byte, 4096)

	n, _ := conn.Read(buffer)
	if n==0{
		return
	}

	fmt.Print("|%s|\n", string(buffer[:n]))

}


GO-http服务器

package main

import (
	"net/http"
	"fmt"
)

func myHandle(w http.ResponseWriter, r *http.Request) {
	// w : 写给客户端的数据内容
	w.Write([]byte("this is a Web server"))

	// r: 从客户端读到的内容
	fmt.Println("Header:", r.Header)
	fmt.Println("URL:", r.URL)
	fmt.Println("Method:", r.Method)
	fmt.Println("Host:", r.Host)
	fmt.Println("RemoteAddr:", r.RemoteAddr)
	fmt.Println("Body:", r.Body)
}

func main()  {
	// 注册回调函数, 该函数在客户端访问服务器时,会自动被调用
	//http.HandleFunc("/itcast", myHandle)
	http.HandleFunc("/", myHandle)

	// 绑定服务器监听地址
	http.ListenAndServe("127.0.0.1:8000", nil)
}


Go-http读取文件夹目录显示到客户端

package main

import (
	"net/http"
	"fmt"
	"os"
)

func OpenSendFile(fNmae string, w http.ResponseWriter)  {
	pathFileName := "E:/go" + fNmae
	f, err := os.Open(pathFileName)
	if err != nil {
		fmt.Println("Open err:", err)
		w.Write([]byte(" No such file or directory !"))
		return
	}
	defer f.Close()

	buf := make([]byte, 4096)
	for {
		n, _ := f.Read(buf)			// 从本地将文件内容读取。
		if n == 0 {
			return
		}
		w.Write(buf[:n])			// 写到 客户端(浏览器)上
	}
}

func myHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("客户端请求:", r.URL)
	fmt.Println(r.URL.String())
	OpenSendFile(r.URL.String(), w)
}

func main()  {
	// 注册回调函数
	http.HandleFunc("/", myHandler)
	// 绑定监听地址
	http.ListenAndServe("127.0.0.1:8000", nil)
}

Go-http客户端

package main

import (
	"net/http"
	"fmt"
	"io"
)

func main()  {
	// 使用Get方法获取服务器响应包数据
	resp, err := http.Get("http://www.baidu.com")
	//resp, err := http.Get("http://127.0.0.1:8000/abc.txt")
	if err != nil {
		fmt.Println("Get err:", err)
		return
	}
	defer resp.Body.Close()

	// 获取服务器端读到的数据
	fmt.Println("Status = ", resp.Status)           // 状态
	fmt.Println("StatusCode = ", resp.StatusCode)   // 状态码
	fmt.Println("Header = ", resp.Header)           // 响应头部
	fmt.Println("Body = ", resp.Body)               // 响应包体

	buf := make([]byte, 4096)         // 定义切片缓冲区,存读到的内容
	var result string
	// 获取服务器发送的数据包内容
	for {
		n, err := resp.Body.Read(buf)  // 读body中的内容。
		if n == 0 {
			fmt.Println("--Read finish!")
			break
		}
		if err != nil && err != io.EOF {
			fmt.Println("resp.Body.Read err:", err)
			return
		}

		result += string(buf[:n])     // 累加读到的数据内容
	}
	// 打印从body中读到的所有内容
	fmt.Println("result = ", result)
}


 类似资料: