1 Star 0 Fork 29

tracese / notebook

forked from JustryDeng / notebook 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
[16]搭建HTTP服务端.md 1.63 KB
一键复制 编辑 原始数据 按行查看 历史
JustryDeng 提交于 2021-08-06 02:00 . ForkJoin

搭建HTTP服务端


ListenAndServe函数

ListenAndServe函数是用来侦听并启动服务的,它同时完成了绑定ip和端口、启动侦听、提供HTTP服务的作用。

格式:

func ListenAndServe(addr string, handler Handler) error

  • addr:服务器地址
  • handler:服务器提供服务的函数指针,一般填nil

HandleFunc函数

如果说ListenAndServe函数是用来提供HTTP服务的,那么HandleFunc函数就是用来处理HTTP请求的了。

格式:

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

  • pattern:路由规则
  • handler func(ResponseWriter, *Request):路由处理函数

搭建HTTP服务端(示例)

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

func main() {
	// 添加路由处理器
	http.HandleFunc("/hello", HelloServer)
	http.HandleFunc("/bye", ByeServer)
	// 创建http服务端
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

func HelloServer(w http.ResponseWriter, req *http.Request) {
	io.WriteString(w, "hello world~\n")
}

func ByeServer(w http.ResponseWriter, req *http.Request) {
	io.WriteString(w, "Bye, Bye!\n")
}

启动,访问:

1

2


相关资料

  • 《Go语言区块链应用开发从入门到精通》 高野 编著
1
https://gitee.com/Trace001/notebook.git
git@gitee.com:Trace001/notebook.git
Trace001
notebook
notebook
master

搜索帮助