利用go的tcp网络编程Api实现一个简单的http服务器,直接上代码(涉及的概念较多)
package main
import (
"fmt"
"net"
"strconv"
)
//用来转化int为string
type Int int
func (i Int)toStr()string {
return strconv.FormatInt(int64(i),10)
}
func testConn(conn net.Conn){
addr := conn.RemoteAddr()
fmt.Println(addr)
//返回的http消息体
var respBody = "<h1>Hello World<h1>"
i := (Int)(len(respBody))
fmt.Println("响应的消息体长度:"+i.toStr())
//返回的http消息头
var respHeader = "HTTP/1.1 200 OK\n"+
"Content-Type: text/html;charset=ISO-8859-1\n"+
"Content-Length: "+i.toStr()
//拼装http返回的消息
resp := respHeader +"\n\r\n"+ respBody
fmt.Println(resp)
n, _ := conn.Write([]byte(resp))
fmt.Printf("发送的数据数量:%s\n",(Int)(n).toStr())
}
func main() {
listen, err := net.Listen("tcp", "0.0.0.0:8888")
if err !=nil{
fmt.Println(err)
return
}
defer listen.Close() //延时关闭 listen
for{
conn, err := listen.Accept()
if err !=nil{
fmt.Println(err)
continue
}
go testConn(conn)
}
}
运行程序
打开浏览器访问http://127.0.0.1:8888
这只是helloworld级别的;跟深入的还需要 了解掌握 http协议,网络7层模型等相关网络知识。