go语言对http协议的支持

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

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

服务器端的几个概念

  • Request:用户请求的信息,用来解析用户的请求信息,包括 post、get、cookie、url 等信息

  • Response:服务器需要反馈给客户端的信息

  • Conn:用户的每次请求链接

  • Handler:处理请求和生成返回信息的处理逻辑

http报文的组成

  • 请求行
  • 请求头
  • 请求体
  • 响应头
  • 响应体

多种请求方式:

  • GET:向服务器请求资源地址
  • POST:直接返回请求内容
  • HEAD:只要求响应头
  • PUT:创建资源
  • DELETE:删除资源
  • TRACE:返回请求本身
  • OPTIONS:返回服务器支持HTTP方法列表、
  • CONNECT:建立网络连接
  • PATCH :修改资源

软件模型

  • B/S结构,客户端浏览器/服务器,客户端是运行在浏览器中
  • C/S结构,客户端/服务器,客户端是独立的软件

HTTP POST 简易模型

go对HTTP的支持

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

Handle Func()可以设置函数的请求路径

LIstenAndServer实现监听服务

单控制器

发给处理器(Handler)

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

http.ServeMux实现了Handler接口

多控制器

在实际开发中大部分情况是不应该只有一个控制器的,不同的诗求应该交给不同的处理单元.

在Golang中支持两种多处理方式

  • 多个处理器(Handler)

  • 多个处理函数(HandleFunc)

使用多处理器

  • 使用http.Handle把不同的URL绑定到不同的处理器

  • 在浏览器中输入http://localhost:8090/myhandler或http://ocalhost:8090/myother可以访问两个处理器
    方法.但是其他URI会出现404(资源未找到)页面

    package main

    import "net/http"

    type MyHandler struct {
    }
    type MyHandle struct {
    }

    func (m *MyHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("MyHandle--第二个"))
    }

    func (m *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("MyHandler"))
    }

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

使用多处理函数

复制代码
func first(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "多函数first")
}
func second(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "多函数second")
}

func main() {
    server := http.Server{Addr: "localhost:8090"}
    http.HandleFunc("/first", first)
    http.HandleFunc("/second", second)
    server.ListenAndServe()
}

获取请求头

复制代码
package main

import (
    "fmt"
    "net/http"
)

func param(w http.ResponseWriter, r *http.Request) {
    h := r.Header //map
    fmt.Fprintln(w, h)
    for _, n := range h["Accept-Language"] {
       fmt.Fprintln(w, n)
    }
}

func main() {
    server := http.Server{Addr: ":8090"}
    http.HandleFunc("/param", param)
    server.ListenAndServe()
}

获取请求参数

可以一次性全部获取也可以按照名称获取

相关推荐
不可能的是1 天前
前端 SSE 流式请求三种实现方案全解析
前端·http
花酒锄作田5 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054965 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月5 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237175 天前
C语言-数组练习进阶
c语言·开发语言·算法