summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/pseudomuto/protoc-gen-doc/extensions/google_api_http/google_api_http.go
blob: cbc5ad14cf3ab4366e1260cb74cd0c175ac39811 (plain) (blame)
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
package extensions

import (
	"net/http"

	"github.com/pseudomuto/protoc-gen-doc/extensions"
	"google.golang.org/genproto/googleapis/api/annotations"
)

// HTTPRule represents a single HTTP rule from the (google.api.http) method option extension.
type HTTPRule struct {
	Method  string `json:"method"`
	Pattern string `json:"pattern"`
	Body    string `json:"body,omitempty"`
}

// HTTPExtension contains the rules set by the (google.api.http) method option extension.
type HTTPExtension struct {
	Rules []HTTPRule `json:"rules"`
}

func getRule(r *annotations.HttpRule) (rule HTTPRule) {
	switch r.GetPattern().(type) {
	case *annotations.HttpRule_Get:
		rule.Method = http.MethodGet
		rule.Pattern = r.GetGet()
	case *annotations.HttpRule_Put:
		rule.Method = http.MethodPut
		rule.Pattern = r.GetPut()
	case *annotations.HttpRule_Post:
		rule.Method = http.MethodPost
		rule.Pattern = r.GetPost()
	case *annotations.HttpRule_Delete:
		rule.Method = http.MethodDelete
		rule.Pattern = r.GetDelete()
	case *annotations.HttpRule_Patch:
		rule.Method = http.MethodPatch
		rule.Pattern = r.GetPatch()
	case *annotations.HttpRule_Custom:
		custom := r.GetCustom()
		rule.Method = custom.GetKind()
		rule.Pattern = custom.GetPath()
	}
	rule.Body = r.GetBody()
	return
}

func init() {
	extensions.SetTransformer("google.api.http", func(payload interface{}) interface{} {
		var rules []HTTPRule
		rule, ok := payload.(*annotations.HttpRule)
		if !ok {
			return nil
		}

		rules = append(rules, getRule(rule))

		// NOTE: The option can only have one level of nested AdditionalBindings.
		for _, rule := range rule.AdditionalBindings {
			rules = append(rules, getRule(rule))
		}

		return HTTPExtension{Rules: rules}
	})
}