Golang net/http使用简析

本文简要分析了Golang的net/http包的使用,包括路由注册、响应函数HandlerFunc的定义、如何解析请求参数,以及http.ListenAndServe启动服务的方法。同时,解释了http.Request和http.Response结构,特别是Request.Body和Header的用途,以及如何通过Request.ParseForm()解析参数。此外,提到了http.Client、http.Server、http.Header和Cookie等关键概念。
摘要由CSDN通过智能技术生成
net/http使用简析

  • 路由:路由注册在http.HandlerFunc(Path,handlerfunc)//接收一个资源定位的路径和一个响应函数
  • 响应函数HandlerFunc(http.ResponseWriter,*http.Request)//其中http.Writer是一个接口实现了客户端消息的封装,Request获取客户端请求内容
  • 在接收参数时需要手动request.ParseForm()解析参数
  • http.ListenAndServe(Addr,handler)//启动服务,handler一般为空
结构解析
  • http.Request是客户端发出的或者服务端收到的相关信息,Request.Body和Request.Header对应请求头和消息内容,获取json数据时应当使用Body

  • http.Response{
    Status string // e.g. “200 OK”
    StatusCode int // e.g. 200
    Proto string // e.g. “HTTP/1.0”
    ProtoMajor int // e.g. 1
    ProtoMinor int // e.g. 0

    }Response对应http回复相关信息

  • Request.Form//请求头中的参数

  • Request.ParseForm()//解析URL中的查询字符串,并将解析结果更新到Form字段。

  • http.Client//http客户端

type Client struct {
   
    Transport RoundTripper
    CheckRedirect func(req *Request, via []*Request) error
    Jar CookieJar
    Timeout time.Duration
}
常用方法:对应http中客户端发起的请求
func (c *Client) Head(url string) (resp *Response, err error)
func (c *Client) Get(url string) (resp *Response, err error)
func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
  • http.Server
	type Server struct {
   
		Addr           string       
		Handler        Handler     
		ReadTimeout    time.Duration 
		WriteTimeout   time.Duration
		MaxHeaderBytes int         
		TLSConfig      *tls.Config   
		TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
		ConnState func(net.Conn, ConnState)
		ErrorLog *log.Logger
	}Server中的字段是http服务端的配置信息
	func (srv *Server) Serve
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值