goWeb简单控制器的实现

43 篇文章 1 订阅
30 篇文章 0 订阅

一. 单控制器

- 在Golang的net/http包下有ServeMux实现了Front设计模式的Front窗口,ServeMux负责接收请求并把请求分发给处理器(Handler)
- http.ServeMux实现了Handler接口
type Handler interface {
	ServeHTTP(ResponseWriter, *Request)
}
type ServeMux struct {
	mu    sync.RWMutex
	m     map[string]muxEntry
	hosts bool // whether any patterns contain hostnames
}
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
	if r.RequestURI == "*" {
		if r.ProtoAtLeast(1, 1) {
			w.Header().Set("Connection", "close")
		}
		w.WriteHeader(StatusBadRequest)
		return
	}
	h, _ := mux.Handler(r)
	h.ServeHTTP(w, r)
}

可以自定义结构体,实现Handler接口后,这个结构体就属于一个处理器,可以处理全部请求

无论在浏览器中输入的资源地址是什么,都可以访问ServeHTTP

实例如下:

package main

import "fmt"
import "net/http"

type MyHandler struct {
}

func (mh *MyHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
   fmt.Fprintln(res,"使用结构体实现单控制器")
}

func main() {
   myhandler := MyHandler{}
   server := http.Server{
      Addr:    "127.0.0.1:8090",
      Handler: &myhandler,
   }
   server.ListenAndServe()
}

二.多控制器

  • 在实际开发中大部分情况是不应该只有一个控制器的,不同的请求应该交给不同的处理单元.在Golang中支持两种多处理方式
    • 多个处理器(Handler)
    • 多个处理函数(HandleFunc)
  • 使用多处理器
    • 使用http.Handle把不同的URL绑定到不同的处理器
    • 在浏览器中输入http://localhost:8090/myhandler或http://localhost:8090/myother可以访问两个处理器方法.但是其他URl会出现404(资源未找到)页面
package main

import (
	"fmt"
	"net/http"
)

//定义两个结构体
type MyHander struct {
}
type MyHandle struct {
}

/*
在函数中调用结构体
*/
func (m *MyHandle)	ServeHTTP(w http.ResponseWriter,r *http.Request)  {
	w.Write([]byte("MyHandle的数据-->第一个"))
}
func (m *MyHander)	ServeHTTP(w http.ResponseWriter,r *http.Request)  {
	w.Write([]byte("MyHander的数据-->第二个"))
}

func main()  {
	h1:=MyHandle{}	
	h2:=MyHander{}	
	server := http.Server{Addr:"localhost:8090"}
	http.Handle("/first",&h1)
	http.Handle("/second",&h2)
	server.ListenAndServe()
}

运行结果如下:

运行后打开localhost:8090/second网址

结果为:

在这里插入图片描述

输入localhost:8090/second

结果为:

在这里插入图片描述

  • 多函数方式要比多处理器方式简便.直接把资源路径与函数绑定
package main

import "fmt"
import "net/http"

//不需要定义结构体
//函数的参数需要按照ServeHTTP函数参数列表进行定义
func first(res http.ResponseWriter, req *http.Request) {
   fmt.Fprintln(res, "第一个")
}
func second(res http.ResponseWriter, req *http.Request) {
   fmt.Fprintln(res, "第二个")
}

func main() {
   server := http.Server{
      Addr: "localhost:8090",
   }
   //注意此处使用HandleFunc函数
   http.HandleFunc("/first", first)
   http.HandleFunc("/second", second)
   server.ListenAndServe()
}

运行解果同上

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值