go编程:实现简单http服务 用 Handler 来选择网站不同页面

不废话,上代码,代码里有注释,看注释就行了。

package main
import (  "net/http")
// 自定义 aboutHandlertype aboutHandler struct{}
func (h *aboutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {  w.Write([]byte("关于我们"))}
// 自定义 cateHandlertype cateHandler struct{}
// ServeHTTP是cateHandler类型的方法(也是一种函数)func (h *cateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {  w.Write([]byte("分类页面"))}
func list(w http.ResponseWriter, r *http.Request) {  w.Write([]byte("列表页面"))}
func tags(w http.ResponseWriter, r *http.Request) {  w.Write([]byte("TAGS页面"))}
func main() {  //DefaultServerMax,默认路由,意思是在根地址下监听,如果有其它路径响应,一律按根地地请求处理  //http.Handle函数有两个参数,第二个是个Handler  //第一个是监听的网络地址,如果为空字符串"",则表是80端口  //第二个是handle,如果值为 nil ,则表示是 DefaultServerMax ,即 multiplexer(多路复用器) 可以看作是路由器  //http.ListenAndServe("localhost:8888", nil)  //以下是 http.ListenAndServe("localhost:8888", nil) 更常用更灵活的写法  server := http.Server{    //网络地址    Addr: "localhost:8888",    //值为 nil ,是 DefaultServerMax 即最前面的 Handler    Handler: nil,  }
  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {    w.Write([]byte("这是GO服务器的首页!"))  })
  //使用 http.Handle 函数处理不同的 handle ,实现转发到处种路径/页面  a := aboutHandler{}  http.Handle("/about", &a)
  c := cateHandler{}  http.Handle("/cate", &c)
  //使用 http.HandleFunc 函数,注:在go源码内部还是调用http.Handle函数  http.HandleFunc("/list", list) //注意:list 不要写成list(),加小括号就执行函数了。这里是传入函数  //使用http.HandlerFunc函数:http.HandlerFunc(tags)是把tags这个函数转换成一个Handler类型。  http.HandleFunc("/tags", http.HandlerFunc(tags))
  //server.ListenAndServe要放所有handle后面  server.ListenAndServe()}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值