Go Web基础

go web基础

HTTP

  • Http:无状态协议,是互联网中使用Http实现计算机和计算机之间的请求和响应

    • Http使用纯文本方式发送和接收协议数据,不需要借助专门工具进行分析就可以知道协议中数据

  • Http报文(message)组成部分

    • 请求行(request-line)

    • 请求头(head)

    • 请求体(body)

    • 响应头

    • 响应体

  • HTTP1.1实现了多种请求方式

    • GET:向服务器请求资源地址

    • HEAD:只要响应头

    • POST:直接返回请求内容

    • PUT:创建资源

    • DELETE:删除资源

    • TRACE:返回请求本身

    • OPTIONS:返回服务器支持HTTP方法列表

    • CONNECT:建立网络连接

    • PATCH:修改资源

  • 软件模型

    • B/S结构,客户端浏览器/服务器,客户端是运行在浏览器中

    • C/S结构,客户端/服务器,客户端时独立的软件

  • HTTP POST简易模型图

GO语言对HTTP支持

  • 在Golang的net/http包提供了HTTP客户端和服务端的实现

  • HandleFunc()可以设置函数的请求路径

// HandleFunc registers the handler function for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func HandleFunc(pattern string,handler func(ResponseWriter,*Request)) {
    DefaultServeMux.HandleFunc(pattern,handler)
}
  • ListenAndServe实现了监听服务

// ListenAndServe always returns a non-nil error.
func ListenAndServe(addr string, handler Handler) error {
    server := &Server{Addr: addr, Handler: handler}
    return server.ListenAndServe()
}
  • 代码实现

package main

import (
	"fmt"
	"net/http"
)

func welcome(res http.ResponseWriter, req *http.Request) {
	res.Header().Set("Content-Type", "text/html;charset=utf-8")
	fmt.Fprintln(res, "Hello world Golang Web <b>Prisoner<b/>")
}

func main() {
	http.HandleFunc("/", welcome)
	http.ListenAndServe("localhost:8081", nil)
}

单控制器

  • 在Golang的net/http包下有ServeMux实现了Front设计模式的Front窗口,ServeMux负责接收请求并把请求分发给处理器(Handler)

  • http.ServeMux实现了Handler接口

type Handle 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接口后,这个结构体就属于一个处理器,可以处理全部请求

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

  • 代码实现

    package main
    
    import (
    	"fmt"
    	"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:    "localhost:8090",
    		Handler: &myhandler,
    	}
    	server.ListenAndServe()
    }
    

多控制器

  • 在实际开发中大部分情况是不应该只有一个控制器的,不同的请求应该交给不同的处理单元。在Golang中支持两种多处理方式

    • 多个处理器(Handler)

    • 多个处理函数(HandleFunc)

  • 使用多处理器

  • 代码实现

    package main
    
    import (
    	"net/http"
    )
    
    type MyHandler struct {
    }
    
    type MyHandle struct {
    }
    
    func (mh *MyHandle) ServeHTTP(res http.ResponseWriter, req *http.Request) {
    	res.Write([]byte("多处理器-MyHandle返回的数据!!!"))
    }
    
    func (mh *MyHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
    	res.Write([]byte("多处理器-MyHandler返回的数据!!!"))
    }
    
    func main() {
    	myhandler := MyHandler{}
    	myhandle := MyHandle{}
    	server := http.Server{
    		Addr: "localhost:8090",
    	}
    	http.Handle("/myhandler", &myhandler)
    	http.Handle("/myhandle", &myhandle)
    	server.ListenAndServe()
    }
    

多函数

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

  • 代码实现

    package main
    
    import "net/http"
    
    func MyHandle(res http.ResponseWriter, req *http.Request) {
    	res.Write([]byte("多函数-MyHandle返回的数据!!!"))
    }
    
    func MyHandler(res http.ResponseWriter, req *http.Request) {
    	res.Write([]byte("多函数-MyHandler返回的数据!!!"))
    }
    
    func main() {
    	server := http.Server{Addr: "localhost:8090"}
    	http.HandleFunc("/MyHandle", MyHandle)
    	http.HandleFunc("/MyHandler", MyHandler)
    	server.ListenAndServe()
    }
    

获取请求头

  • 在浏览器地址栏中输入下面信息,这属于http请求的get方式,请求携带两个参数

    http://localhost:8090/param?name=zhang&age=18

  • 代码实现

    package main
    
    import (
    	"fmt"
    	"net/http"
    	"strings"
    )
    
    func param(res http.ResponseWriter, req *http.Request) {
    	header := req.Header
    	fmt.Fprintln(res, header)
    	fmt.Fprintln(res, header["Accept-Encoding"])
    	fmt.Fprintln(res, len(header["Accept-Encoding"]))
    	for _, n := range strings.Split(header["Accept-Encoding"][0], ",") {
    		fmt.Fprintln(res, strings.TrimSpace(n))
    	}
    }
    
    func main() {
    	server := http.Server{Addr: "localhost:8090"}
    	http.HandleFunc("/param", param)
    	server.ListenAndServe()
    }
    

获取请求参数

  • 请求参数可以一次全部获取也可以按照名称获取

  • 代码实现

    package main
    
    import (
    	"fmt"
    	"net/http"
    	"strings"
    )
    
    func param(res http.ResponseWriter, req *http.Request) {
    	header := req.Header
    	fmt.Fprintln(res, header)
    	fmt.Fprintln(res, header["Accept-Encoding"])
    	fmt.Fprintln(res, len(header["Accept-Encoding"]))
    	for _, n := range strings.Split(header["Accept-Encoding"][0], ",") {
    		fmt.Fprintln(res, strings.TrimSpace(n))
    	}
    }
    
    func main() {
    	server := http.Server{Addr: "localhost:8090"}
    	http.HandleFunc("/param", param)
    	server.ListenAndServe()
    }
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值