go编写简单的http服务

Posted by hiho on July 25, 2019

net/http包

go语言中,网络模块的包在net中,其中net/http是http模块,所以需要引入该模块

import (
	"net/http"
)

编写源码

然后通过http.ListenAndServe监听端口,已经http.HandleFunc处理访问事件



func main() {
    http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
    	writer.Write([]byte("Here is the home page."))
    })
    
    http.ListenAndServe(":8080", nil)
}

启动服务

然后终端执行

go run main.go

打开浏览器访问localhost:8080,就会输出Here is the home page.

1.png

—End—

迭代

  • 2019年07月25日 18:19 初稿

参考