github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/easy/ezhttp/utils.go (about) 1 package ezhttp 2 3 import ( 4 "encoding/xml" 5 "io" 6 "net/http" 7 "regexp" 8 9 "github.com/jxskiss/gopkg/v2/perf/json" 10 ) 11 12 var ( 13 jsonCheck = regexp.MustCompile(`(?i:(application|text)/(json|.*\+json|json\-.*)(;|$))`) 14 xmlCheck = regexp.MustCompile(`(?i:(application|text)/(xml|.*\+xml)(;|$))`) 15 ) 16 17 // DecodeJSON decodes a json value from r. 18 func DecodeJSON(r io.Reader, v any) error { 19 data, err := io.ReadAll(r) 20 if err != nil { 21 return err 22 } 23 return json.Unmarshal(data, v) 24 } 25 26 // IsJSONType method is to check JSON content type or not. 27 func IsJSONType(contentType string) bool { 28 return jsonCheck.MatchString(contentType) 29 } 30 31 // DecodeXML decodes a XML value from r. 32 func DecodeXML(r io.Reader, v any) error { 33 data, err := io.ReadAll(r) 34 if err != nil { 35 return err 36 } 37 return xml.Unmarshal(data, v) 38 } 39 40 // IsXMLType method is to check XML content type or not. 41 func IsXMLType(contentType string) bool { 42 return xmlCheck.MatchString(contentType) 43 } 44 45 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods 46 func mayHaveBody(method string) bool { 47 switch method { 48 case http.MethodConnect, 49 http.MethodGet, 50 http.MethodHead, 51 http.MethodOptions, 52 http.MethodTrace: 53 return false 54 } 55 // DELETE, PATCH, POST, PUT 56 return true 57 }