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
- Go指南练习之《HTTP 处理》
- Go指南练习之《slice》
- Go指南练习之《map》
- Go指南练习之《Stringers》
- Go指南练习之《错误》
- Go指南练习之《斐波纳契闭包》
- Go指南练习之《Reader》
- Go指南练习之《rot13Reader》
- Go指南练习之《图片》
- Go指南练习之《斐波纳契闭包》
- Go指南练习之《循环和函数》
- Go指南练习之《等价二叉树》
- Go指南练习之《Web 爬虫》
- Go指南中的练习:map
- Go指南中的练习:Stringers
- go语言指南的练习
- Go指南—练习:rot13Reader
- go http异常处理
- 使用 TeamCity 实现持续集成(CI)
- SAS程序
- 【解析HTML】HTML解析,网络爬虫
- USACO1.3 混合牛奶Mixing Milk
- 银联开发报 java.security.NoSuchProviderException: no such provider: BC
- Go指南练习之《HTTP 处理》
- vim使用教程
- PyAutoGUI 简介【转】
- Linux 设置桌面快捷键
- vb中DoEvents是什么意思
- Opencv之<Vec3b>是什么东东
- 判断是否为平衡二叉树
- iOS10系统之后页面disappear 调用scrollviewdidscroll方法
- oracle运用(八) oracle中的日期查询二