github.com/googleapis/api-linter@v1.65.2/rules/aip0133/http_body.go (about) 1 // Copyright 2019 Google LLC 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 // https://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 package aip0133 16 17 import ( 18 "fmt" 19 "strings" 20 21 "github.com/googleapis/api-linter/lint" 22 "github.com/googleapis/api-linter/locations" 23 "github.com/googleapis/api-linter/rules/internal/utils" 24 "github.com/jhump/protoreflect/desc" 25 ) 26 27 // Create methods should have an HTTP body, and the body value should be resource. 28 var httpBody = &lint.MethodRule{ 29 Name: lint.NewRuleName(133, "http-body"), 30 OnlyIf: utils.IsCreateMethod, 31 LintMethod: func(m *desc.MethodDescriptor) []lint.Problem { 32 resourceMsgName := utils.GetResourceMessageName(m, "Create") 33 resourceFieldName := strings.ToLower(resourceMsgName) 34 for _, fieldDesc := range m.GetInputType().GetFields() { 35 // when msgDesc is nil, the resource field in the request message is 36 // missing. A lint warning for the rule `resourceField` will be generated. 37 // For here, we will use the lower case resource message name as default 38 if msgDesc := fieldDesc.GetMessageType(); msgDesc != nil && msgDesc.GetName() == resourceMsgName { 39 resourceFieldName = fieldDesc.GetName() 40 } 41 } 42 43 // Establish that HTTP body the RPC should map the resource field name in the request message. 44 for _, httpRule := range utils.GetHTTPRules(m) { 45 if httpRule.Body == "" { 46 // Establish that the RPC should have HTTP body 47 return []lint.Problem{{ 48 Message: "Post methods should have an HTTP body.", 49 Descriptor: m, 50 Location: locations.MethodHTTPRule(m), 51 }} 52 // When resource field is not set in the request message, the problem 53 // will not be triggered by the rule"core::0133::http-body". It will be 54 // triggered by another rule 55 // "core::0133::request-message::resource-field" 56 } else if resourceFieldName != "" && httpRule.Body != resourceFieldName { 57 return []lint.Problem{{ 58 Message: fmt.Sprintf( 59 "The content of body %q must map to the resource field %q in the request message", 60 httpRule.Body, 61 resourceFieldName, 62 ), 63 Descriptor: m, 64 Location: locations.MethodHTTPRule(m), 65 }} 66 } 67 } 68 return nil 69 }, 70 }