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/string 和 http://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]
相关文章推荐
- Go指南中的练习:Stringers
- go语言指南的练习
- go语言之行--网络编程、http处理流程详情
- go语言http服务处理image/css/js等静态文件
- 练习Go语言-HTTP压力测试.md
- Go指南—练习:rot13Reader
- Go指南练习之《循环和函数》(Loops and Functions)
- Go指南练习之《错误》(Errors)
- Go指南练习之《Stringers》
- go指南练习:循环和函数
- Go 指南(Go tour)练习:循环和函数
- http.Handler 与Go的错误处理
- Go指南练习之《斐波纳契闭包》(Fibonacci closure)
- Go指南练习之《rot13Reader》
- Go指南练习之《斐波纳契闭包》
- Go 指南(Go tour)练习:map
- Go指南练习之《map》
- Go指南练习之《Web 爬虫》(Web Crawler)
- Go指南中的练习:map
- Go指南练习之《slice》