requests/base.go

55 lines
1.0 KiB
Go

package requests
import (
"bytes"
"errors"
"net/http"
"reflect"
)
func buildBodyRequest(ver, rawurl string, body *Body) *http.Request {
var req *http.Request
var err error
contentType := ""
if body.IOBody == nil {
req, err = http.NewRequest(ver, rawurl, nil)
} else {
var bodybuf *bytes.Buffer
switch body.IOBody.(type) {
case []byte:
bodybuf = bytes.NewBuffer(body.IOBody.([]byte))
case *bytes.Buffer:
bodybuf = bytes.NewBuffer(body.IOBody.(*bytes.Buffer).Bytes())
default:
panic(errors.New("the type is not exist, type is" + reflect.TypeOf(body.IOBody).String()))
}
req, err = http.NewRequest(ver, rawurl, bodybuf)
}
if err != nil {
panic(err)
}
if body.ContentType != "" {
if body.ContentType == TypeContentEmpty {
contentType = ""
} else {
contentType = body.ContentType
}
} else {
if contentType == "" {
if ver == "POST" || ver == "PUT" || ver == "Patch" {
contentType = TypeURLENCODED
}
}
}
if contentType != "" {
req.Header.Set(HeaderKeyContentType, contentType)
}
return req
}