解析器封装请求

 封装请求解析,包括处理HTTP请求报文,解析出请求方法、请求头、请求体、URL路径等信息,以适用GET/POST等各种请求

type Request struct {
	Method  string
	Path    string
	Headers http.Header
	Params  url.Values
	Body    []byte
}

//解析http请求
func parseRequest(r *http.Request) *Request {
	req := &Request{
		Method:  r.Method,
		Path:    r.URL.Path,
		Headers: r.Header,
		Params:  r.URL.Query(),
	}

	if req.Method == http.MethodPost || req.Method == http.MethodPut {
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			// handle error
		}
		req.Body = body
	}

	return req
}

//从net.conn中读取,request可要变
//type Request struct {
//    Method string
//    URL    *url.URL
//    Header http.Header
//   Body   io.ReadCloser
}

func (s *Server) readRequest(conn net.Conn) (*Request, error) {
    r := bufio.NewReader(conn)

    // read request line
    line, err := r.ReadString('\n')
    if err != nil {
        return nil, err
    }

    parts := strings.Split(line, " ")
    if len(parts) != 3 {
        return nil, http.ErrInvalidMethod
    }

    // parse request method and url
    method := parts[0]
    url, err := url.ParseRequestURI(parts[1])
    if err != nil {
        return nil, err
    }

    // read request headers
    headers, err := http.ReadHeader(r)
    if err != nil {
        return nil, err
    }

    // read request body
    body := io.NopCloser(r)

    return &Request{
        Method: method,
        URL:    url,
        Header: headers,
        Body:   body,
    }, nil
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值