github.hscsec.cn/aerogo/aero@v1.0.0/BodyReader.go (about) 1 package aero 2 3 import ( 4 "errors" 5 "io" 6 "io/ioutil" 7 8 jsoniter "github.com/json-iterator/go" 9 ) 10 11 // BodyReader represents a request body. 12 type BodyReader struct { 13 reader io.ReadCloser 14 } 15 16 // JSON parses the body as a JSON object. 17 func (body BodyReader) JSON() (interface{}, error) { 18 if body.reader == nil { 19 return nil, errors.New("Empty body") 20 } 21 22 decoder := jsoniter.NewDecoder(body.reader) 23 defer body.reader.Close() 24 25 var data interface{} 26 err := decoder.Decode(&data) 27 28 if err != nil { 29 return nil, err 30 } 31 32 return data, nil 33 } 34 35 // JSONObject parses the body as a JSON object and returns a map[string]interface{}. 36 func (body BodyReader) JSONObject() (map[string]interface{}, error) { 37 json, err := body.JSON() 38 39 if err != nil { 40 return nil, err 41 } 42 43 data, ok := json.(map[string]interface{}) 44 45 if !ok { 46 return nil, errors.New("Invalid format: Expected JSON object") 47 } 48 49 return data, nil 50 } 51 52 // Bytes returns a slice of bytes containing the request body. 53 func (body BodyReader) Bytes() ([]byte, error) { 54 data, err := ioutil.ReadAll(body.reader) 55 defer body.reader.Close() 56 57 if err != nil { 58 return nil, err 59 } 60 61 return data, nil 62 } 63 64 // String returns a string containing the request body. 65 func (body BodyReader) String() (string, error) { 66 bytes, err := body.Bytes() 67 68 if err != nil { 69 return "", err 70 } 71 72 return string(bytes), nil 73 }