forked from einride/protoc-gen-typescript-http
/
rule.go
94 lines (87 loc) · 2.37 KB
/
rule.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package httprule
import (
"fmt"
"net/http"
"google.golang.org/genproto/googleapis/api/annotations"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
)
func Get(m protoreflect.MethodDescriptor) (*annotations.HttpRule, bool) {
descriptor, ok := proto.GetExtension(m.Options(), annotations.E_Http).(*annotations.HttpRule)
if !ok || descriptor == nil {
return nil, false
}
return descriptor, true
}
type Rule struct {
// The HTTP method to use.
Method string
// The template describing the URL to use.
Template Template
Body string
AdditionalRules []Rule
}
func ParseRule(httpRule *annotations.HttpRule) (Rule, error) {
method, err := httpRuleMethod(httpRule)
if err != nil {
return Rule{}, err
}
url, err := httpRuleURL(httpRule)
if err != nil {
return Rule{}, err
}
template, err := ParseTemplate(url)
if err != nil {
return Rule{}, err
}
additional := make([]Rule, len(httpRule.AdditionalBindings))
for i, r := range httpRule.AdditionalBindings {
a, err := ParseRule(r)
if err != nil {
return Rule{}, fmt.Errorf("parse additional binding %d: %w", i, err)
}
additional[i] = a
}
return Rule{
Method: method,
Template: template,
Body: httpRule.Body,
AdditionalRules: additional,
}, nil
}
func httpRuleURL(rule *annotations.HttpRule) (string, error) {
switch v := rule.GetPattern().(type) {
case *annotations.HttpRule_Get:
return v.Get, nil
case *annotations.HttpRule_Post:
return v.Post, nil
case *annotations.HttpRule_Delete:
return v.Delete, nil
case *annotations.HttpRule_Patch:
return v.Patch, nil
case *annotations.HttpRule_Put:
return v.Put, nil
case *annotations.HttpRule_Custom:
return v.Custom.Path, nil
default:
return "", fmt.Errorf("http rule does not have an URL defined")
}
}
func httpRuleMethod(rule *annotations.HttpRule) (string, error) {
switch v := rule.GetPattern().(type) {
case *annotations.HttpRule_Get:
return http.MethodGet, nil
case *annotations.HttpRule_Post:
return http.MethodPost, nil
case *annotations.HttpRule_Delete:
return http.MethodDelete, nil
case *annotations.HttpRule_Patch:
return http.MethodPatch, nil
case *annotations.HttpRule_Put:
return http.MethodPut, nil
case *annotations.HttpRule_Custom:
return v.Custom.Kind, nil
default:
return "", fmt.Errorf("http rule does not have an URL defined")
}
}