@@ -24,8 +24,6 @@ import (
2424 "github.com/lenye/pmsg/im"
2525)
2626
27- const contentTypeJson = "application/json"
28-
2927func PostJSON (url string , reqBody , respBody any ) (http.Header , error ) {
3028 body , err := im .JsonEncode (reqBody )
3129 if err != nil {
@@ -34,20 +32,23 @@ func PostJSON(url string, reqBody, respBody any) (http.Header, error) {
3432
3533 resp , err := httpclient .Post (url , httpclient .HdrValApplicationJson , body )
3634 if err != nil {
37- return nil , fmt . Errorf ( "%w, %w" , httpclient . ErrRequest , err )
35+ return nil , err
3836 }
3937 defer func (Body io.ReadCloser ) {
4038 _ = Body .Close ()
4139 }(resp .Body )
4240
43- isRespJson := strings .EqualFold (resp .Header .Get ("content-type" ), contentTypeJson )
44- if isRespJson {
45- if err := im .JsonDecode (resp .Body , respBody ); err != nil {
46- return nil , fmt .Errorf ("json decode failed, %w" , err )
47- }
41+ // "application/json" 响应内容类型
42+ // "application/json; charset=utf-8" 错误响应内容类型
43+ contentType := resp .Header .Get ("content-type" )
44+ if ! strings .EqualFold (contentType , httpclient .HdrValApplicationJson ) && ! strings .EqualFold (contentType , httpclient .HdrValApplicationJsonCharset ) {
45+ return nil , fmt .Errorf ("http.response.header.content-type != %s" , httpclient .HdrValApplicationJson )
46+ }
47+ if err := im .JsonDecode (resp .Body , respBody ); err != nil {
48+ return nil , fmt .Errorf ("http.response.body json decode failed, %w" , err )
4849 }
49- if resp .StatusCode / 100 != 2 {
50- return nil , fmt .Errorf ("%w, http response status: %s" , httpclient . ErrRequest , resp .Status )
50+ if resp .StatusCode != http . StatusOK {
51+ return resp . Header , fmt .Errorf ("invalid http. response. status: %s" , resp .Status )
5152 }
5253 return resp .Header , nil
5354}
0 commit comments