您的位置:首页 > 理论基础 > 计算机网络

Go指南练习之《HTTP 处理》

2017-01-22 16:31 351 查看
Go官网指南

练习原文

实现下面的类型,并在其上定义 ServeHTTP 方法。在 web 服务器中注册它们来处理指定的路径。

type String string

type 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/stringhttp://localhost:4000/struct. 
*注意:* 这个例子无法在基于 web 的用户界面下运行。 为了尝试编写 web 服务,你可能需要 安装 Go。


关键信息

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


代码

package main

import (
"fmt"
"log"
"net/http"
)
// 1 定义类型
type String string
type 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[/code] 
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: