[feat] package nazahttp: 新增函数ReadHTTPRequest,读取HTTP请求并解析

pull/2/head
q191201771 4 years ago
parent ee4d4835cf
commit 35b236b424

@ -10,15 +10,14 @@ package nazahttp
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"github.com/q191201771/naza/pkg/nazajson"
)
var ErrParamMissing = errors.New("nazahttp: param missing")
// @brief 从http请求中解析body中的json字符串并反序列化至结构体中
//
// @param r http请求对象
// @param info 输出参数,用于接收反序列化之后的数据
// @param keyFieldList 可选参数可指定一个或多个json中必须存在的字段

@ -9,12 +9,9 @@
package nazahttp
import (
"errors"
"strings"
)
var ErrHTTPHeader = errors.New("nazahttp: fxxk")
type LineReader interface {
ReadLine() (line []byte, isPrefix bool, err error)
}

@ -0,0 +1,21 @@
// Copyright 2020, Chef. All rights reserved.
// https://github.com/q191201771/naza
//
// Use of this source code is governed by a MIT-style license
// that can be found in the License file.
//
// Author: Chef (191201771@qq.com)
package nazahttp
import "errors"
var (
ErrHTTPHeader = errors.New("nazahttp: fxxk")
ErrParamMissing = errors.New("nazahttp: param missing")
)
const (
HeaderFieldContentLength = "Content-Length"
HeaderFieldContentType = "application/json"
)

@ -26,5 +26,5 @@ func PostJson(url string, info interface{}, client *http.Client) (*http.Response
if client == nil {
client = http.DefaultClient
}
return client.Post(url, "application/json", b)
return client.Post(url, HeaderFieldContentType, b)
}

@ -0,0 +1,53 @@
// Copyright 2020, Chef. All rights reserved.
// https://github.com/q191201771/naza
//
// Use of this source code is governed by a MIT-style license
// that can be found in the License file.
//
// Author: Chef (191201771@qq.com)
package nazahttp
import (
"io"
"strconv"
)
// e.g. bufio.Reader
type RequestReader interface {
LineReader
io.Reader
}
type HTTPRequestCtx struct {
Method string
URI string
Headers map[string]string
Body []byte
}
// 注意如果HTTP Header中不包含`Content-Length`则不会读取HTTP Body并且err返回值为nil
func ReadHTTPRequest(r RequestReader) (ctx HTTPRequestCtx, err error) {
var requestLine string
requestLine, ctx.Headers, err = ReadHTTPHeader(r)
if err != nil {
return ctx, err
}
ctx.Method, ctx.URI, _, err = ParseHTTPRequestLine(requestLine)
if err != nil {
return ctx, err
}
contentLength, ok := ctx.Headers[HeaderFieldContentLength]
if !ok {
return ctx, nil
}
cl, err := strconv.Atoi(contentLength)
if err != nil {
return ctx, err
}
ctx.Body = make([]byte, cl)
_, err = io.ReadFull(r, ctx.Body)
return ctx, err
}
Loading…
Cancel
Save