github.com/cloudwego/hertz@v0.9.3/pkg/app/server/binding/internal/decoder/gjson_required.go (about) 1 // Copyright 2023 CloudWeGo Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 16 //go:build gjson || !(amd64 && (linux || windows || darwin)) 17 // +build gjson !amd64 !linux,!windows,!darwin 18 19 package decoder 20 21 import ( 22 "strings" 23 24 "github.com/cloudwego/hertz/internal/bytesconv" 25 "github.com/cloudwego/hertz/pkg/common/utils" 26 "github.com/cloudwego/hertz/pkg/protocol" 27 "github.com/cloudwego/hertz/pkg/protocol/consts" 28 "github.com/tidwall/gjson" 29 ) 30 31 func checkRequireJSON(req *protocol.Request, tagInfo TagInfo) bool { 32 if !tagInfo.Required { 33 return true 34 } 35 ct := bytesconv.B2s(req.Header.ContentType()) 36 if !strings.EqualFold(utils.FilterContentType(ct), consts.MIMEApplicationJSON) { 37 return false 38 } 39 result := gjson.GetBytes(req.Body(), tagInfo.JSONName) 40 if !result.Exists() { 41 idx := strings.LastIndex(tagInfo.JSONName, ".") 42 // There should be a superior if it is empty, it will report 'true' for required 43 if idx > 0 && !gjson.GetBytes(req.Body(), tagInfo.JSONName[:idx]).Exists() { 44 return true 45 } 46 return false 47 } 48 return true 49 } 50 51 func keyExist(req *protocol.Request, tagInfo TagInfo) bool { 52 ct := bytesconv.B2s(req.Header.ContentType()) 53 if utils.FilterContentType(ct) != consts.MIMEApplicationJSON { 54 return false 55 } 56 result := gjson.GetBytes(req.Body(), tagInfo.JSONName) 57 return result.Exists() 58 }