Package Request:

- add content length header helper function
- add control with length of result marshall body with function jsonbody
- add set content length header in function jsonbody
This commit is contained in:
Nicolas JUHEL
2024-02-05 15:00:44 +01:00
parent c66a00917a
commit f7fd908a14
4 changed files with 19 additions and 3 deletions

View File

@@ -32,16 +32,21 @@ import (
"io"
)
const contentTypeJson = "application/json"
const (
contentTypeJson = "application/json"
)
func (r *request) BodyJson(body interface{}) error {
if p, e := json.Marshal(body); e != nil {
return e
} else if len(p) < 1 {
return ErrorInvalidBody.Error()
} else {
r.ContentType(contentTypeJson)
r.ContentLength(uint64(len(p)))
r._BodyReader(bytes.NewBuffer(p))
}
r.ContentType(contentTypeJson)
return nil
}

View File

@@ -36,6 +36,7 @@ const (
ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgRequest
ErrorParamInvalid
ErrorValidatorError
ErrorInvalidBody
ErrorCreateRequest
ErrorSendRequest
ErrorResponseInvalid
@@ -61,6 +62,8 @@ func getMessage(code liberr.CodeError) (message string) {
return "at least one given parameters is invalid"
case ErrorValidatorError:
return "config seems to be invalid"
case ErrorInvalidBody:
return "marshalled body seems to be invalid"
case ErrorCreateRequest:
return "cannot create http request for given params"
case ErrorSendRequest:

View File

@@ -26,12 +26,19 @@
package request
import "net/url"
import (
"fmt"
"net/url"
)
func (r *request) ContentType(mime string) {
r.SetHeader(_ContentType, mime)
}
func (r *request) ContentLength(size uint64) {
r.SetHeader(__ContentLength, fmt.Sprintf("%d", size))
}
func (r *request) CleanHeader() {
r.s.Lock()
defer r.s.Unlock()

View File

@@ -42,6 +42,7 @@ import (
const (
_ContentType = "Content-Type"
__ContentLength = "Content-Length"
_Authorization = "Authorization"
_AuthorizationBearer = "Bearer"
_AuthorizationBasic = "Basic"