Go指南练习之《HTTP 处理》

来源:互联网 发布:西安seo自动优化软件 编辑:程序博客网 时间:2024/05/18 20:09

Go官网指南

练习原文

实现下面的类型,并在其上定义 ServeHTTP 方法。在 web 服务器中注册它们来处理指定的路径。type String stringtype Struct struct {    Greeting string    Punct    string    Who      string}例如,可以使用如下方式注册处理方法:http.Handle("/string", String("I'm a frayed knot."))http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})在启动你的 http 服务器后,你将能够访问: http://localhost:4000/string 和 http://localhost:4000/struct.*注意:* 这个例子无法在基于 web 的用户界面下运行。 为了尝试编写 web 服务,你可能需要 安装 Go。

关键信息

关键是让String  Struct 实现 ServeHTTP 方法 作为http.Handler来处理请求

代码

package mainimport (    "fmt"    "log"    "net/http")// 1 定义类型type String stringtype Struct struct {    Greeting string    Punct    string    Who      string}// 2 实现http.Handler的方法func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) {    fmt.Fprint(w, string(s))}func (s *Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) {    fmt.Fprint(w, fmt.Sprintf("%v", s))} func main() {    // 3  设置需要处理的对应的url    http.Handle("/string", String("I'm a frayed knot."))    http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})    //   这里就是默认的 nil     e := http.ListenAndServe("localhost:4000", nil)    if e != nil {        log.Fatal(e)    }}

运行结果

需要本地运行:

I'm a frayed knot.   ///      http://localhost:4000/string&{Hello : Gophers!}   ///      http://localhost:4000/struct
0 0