Go by Example 中文版: HTTP 服务端

时间:2022-07-24
本文章向大家介绍Go by Example 中文版: HTTP 服务端,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

[Go by Example 中文版](https://gobyexample-cn.github.io/): HTTP 服务端

使用 net/http 包,我们可以轻松实现一个简单的 HTTP 服务器。 示例代码如下:

// Go by Example 中文版:HTTP 服务端
// https://gobyexample-cn.github.io/http-servers
// 使用net/http包,我们可以轻松实现一个简单的HTTP服务器。
package main

import (
	"fmt"
	"net/http"
)

/**
** handlers 是net/http服务器里面的一个基本概念。
** handler 对象实现了http.Handler接口。
** 编写handler的常见方法是,在具有适当签名的函数上使用http.HandlerFunc适配器。
 */

/**
** handler 函数有两个参数,http.ResponseWriter和http.Request。 reponse writer被用于写入HTTP响应数据,
** 这里我们简单的返回"hellon"。
 */
func hello(w http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(w, "hellon")
}

/**
** 这个handler稍微复杂一点,我们需要读取的HTTP请求header中的所有内容,并将他们输出至response body。
 */
func headers(w http.ResponseWriter, req *http.Request) {
	for name, headers := range req.Header {
		for _, h := range headers {
			fmt.Fprintf(w, "%v: %vn", name, h)
		}
	}
}

func main() {
	/**
	** 使用 http.Handler函数,可以方便的将我们的handler注册到服务器路由。它是net/http包中的默认路由,
	** 接受一个函数作为参数。
	 */
	http.HandleFunc("/hello", hello)
	http.HandleFunc("/headers", headers)

	// 最后,我们调用ListenAndServe 并带上端口和handler。
	// nil表示使用我们刚刚设置的默认路由器。
	http.ListenAndServe(":8090", nil)
}

后台运行服务器。

$ go run http-servers.go &

访问 /hello路由。

$ curl localhost:8090/hello
hello

使用curl分别访问/helloheaders路由如下图所示:

在Google Chorme浏览器中访问http://localhost:8090/hello输出如下图所示的信息:

再访问http://localhost:8090/headers路由,如下图所示: