Chapter 10_Network Programming, 34_Network Programming_http Response Packet Format

TCP write client, connect to the HTTP server, use the request packet to access the server, and print the response message returned by the server.

Source code

package main

import (
	"fmt"
	"net"
)

func main() {
    
    
	//主动连接服务器
	conn, err1 := net.Dial("tcp", ":8000")
	if err1 != nil {
    
    
		fmt.Println("net.Dial err1 = ", err1)
		return
	}
	defer conn.Close()

	requestBuf := "GET /go HTTP/1.1\r\nAccept: image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/xaml+xml, application/x-ms-xbap, */*\r\nAccept-Language: zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)\r\nAccept-Encoding: gzip, deflate\r\nHost: 127.0.0.1:8000\r\nConnection: Keep-Alive\r\n\r\n"

	conn.Write([]byte(requestBuf))
	buf := make([]byte, 1024*4)
	n, err2 := conn.Read(buf)
	if n == 0 {
    
    
		fmt.Println("conn.Read err2 = ", err2)
		return
	}

	//打印响应的报文
	fmt.Printf("#%v#", string(buf[:n]))
}

Printout

//打印
//1、正常响应,GET /go
/*
#HTTP/1.1 200 OK							//状态行,状态码200
Date: Wed, 03 Mar 2021 12:58:18 GMT			//响应头部
Content-Length: 9
Content-Type: text/plain; charset=utf-8
											//空行
hello go									//响应包体
*/

//2、错误响应,GET /go(加错误路径)
/*
#HTTP/1.1 404 Not Found						//状态行,状态码404
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Date: Wed, 03 Mar 2021 12:59:40 GMT
Content-Length: 19

404 page not found
#
*/

Guess you like

Origin blog.csdn.net/weixin_40355471/article/details/115288623