封装请求解析,包括处理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
}