Compare commits
85 Commits
Author | SHA1 | Date | |
---|---|---|---|
5ecd91182f | |||
a8b52d800d | |||
6d17a74ffb | |||
55fa1ee403 | |||
9c05b6b646 | |||
675ca27dbf | |||
f22d8ed055 | |||
3806fb9336 | |||
a0385eff9c | |||
0f957b897b | |||
9bad6b85f3 | |||
9cc9e19e0b | |||
93e5f2ee90 | |||
255a9712dc | |||
7a1be4f903 | |||
489c58fae7 | |||
25ad4ed647 | |||
1bdd68d6ea | |||
dbaa0089b6 | |||
2f9003161b | |||
388a58d998 | |||
d519d8ac6d | |||
92e78b6754 | |||
e25d0cdf02 | |||
71ad836e06 | |||
|
16a4ceaf26 | ||
|
5c4a300a4f | ||
|
821949fed3 | ||
|
b35607a63e | ||
|
da5d5191db | ||
0d2781dfc9 | |||
edd1ba2175 | |||
83b6567d3e | |||
|
e545d81720 | ||
|
a3cf27d062 | ||
|
bc4de7e632 | ||
|
53ed35a106 | ||
|
94b653cbe8 | ||
|
3d887ac2bf | ||
|
a58a9d5173 | ||
|
f072294110 | ||
|
e8389ad0f8 | ||
|
adb15d9a67 | ||
|
78a508f48d | ||
80ed8fba15 | |||
|
a9d41f3adb | ||
a73c4b836f | |||
|
e587b778b2 | ||
b950206585 | |||
|
773793955d | ||
3591d02d42 | |||
a2fea36f50 | |||
03355d0d83 | |||
15e7f6bd16 | |||
a2da7d4ceb | |||
211999bb04 | |||
59ffe0f3ea | |||
378c00c16d | |||
|
4f0a7e0c93 | ||
8844f01558 | |||
7c25072247 | |||
65151b3e3e | |||
ad0fd42945 | |||
|
8ecb705550 | ||
|
225887fef8 | ||
41e32e36b3 | |||
e6b8324395 | |||
2da3760acb | |||
6e47e59542 | |||
fc716500c4 | |||
|
8d8d570880 | ||
ed7ae1c518 | |||
3e6e9eb469 | |||
26370e69f2 | |||
c996b37985 | |||
d63381e584 | |||
|
a231083367 | ||
e52e4b2e19 | |||
|
752dee776a | ||
9cfdf9539f | |||
a47e8c074b | |||
|
67e5e64aa6 | ||
8afbf92aea | |||
f6cfb2de1e | |||
f814b489db |
20
.github/workflows/autoapprove.yml
vendored
Normal file
20
.github/workflows/autoapprove.yml
vendored
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
name: "autoapprove"
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request_target:
|
||||||
|
types: [assigned, opened, synchronize, reopened]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
pull-requests: write
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
autoapprove:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: approve
|
||||||
|
uses: hmarr/auto-approve-action@v3
|
||||||
|
if: github.actor == 'vtolstov' || github.actor == 'dependabot[bot]'
|
||||||
|
id: approve
|
||||||
|
with:
|
||||||
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
21
.github/workflows/automerge.yml
vendored
Normal file
21
.github/workflows/automerge.yml
vendored
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
name: "automerge"
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request_target:
|
||||||
|
types: [assigned, opened, synchronize, reopened]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
pull-requests: write
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
automerge:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.actor == 'vtolstov'
|
||||||
|
steps:
|
||||||
|
- name: merge
|
||||||
|
id: merge
|
||||||
|
run: gh pr merge --auto --merge "$PR_URL"
|
||||||
|
env:
|
||||||
|
PR_URL: ${{github.event.pull_request.html_url}}
|
||||||
|
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
13
.github/workflows/build.yml
vendored
13
.github/workflows/build.yml
vendored
@ -3,19 +3,20 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
|
- v3
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
name: test
|
name: test
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: setup
|
- name: setup
|
||||||
uses: actions/setup-go@v2
|
uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
go-version: 1.16
|
go-version: 1.17
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
- name: cache
|
- name: cache
|
||||||
uses: actions/cache@v2
|
uses: actions/cache@v3
|
||||||
with:
|
with:
|
||||||
path: ~/go/pkg/mod
|
path: ~/go/pkg/mod
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
@ -31,9 +32,9 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
- name: lint
|
- name: lint
|
||||||
uses: golangci/golangci-lint-action@v2
|
uses: golangci/golangci-lint-action@v3.4.0
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||||
|
29
.github/workflows/codeql-analysis.yml
vendored
29
.github/workflows/codeql-analysis.yml
vendored
@ -9,7 +9,7 @@
|
|||||||
# the `language` matrix defined below to confirm you have the correct set of
|
# the `language` matrix defined below to confirm you have the correct set of
|
||||||
# supported CodeQL languages.
|
# supported CodeQL languages.
|
||||||
#
|
#
|
||||||
name: "CodeQL"
|
name: "codeql"
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_run:
|
workflow_run:
|
||||||
@ -17,16 +17,16 @@ on:
|
|||||||
types:
|
types:
|
||||||
- completed
|
- completed
|
||||||
push:
|
push:
|
||||||
branches: [ master ]
|
branches: [ master, v3 ]
|
||||||
pull_request:
|
pull_request:
|
||||||
# The branches below must be a subset of the branches above
|
# The branches below must be a subset of the branches above
|
||||||
branches: [ master ]
|
branches: [ master, v3 ]
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '34 1 * * 0'
|
- cron: '34 1 * * 0'
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
analyze:
|
analyze:
|
||||||
name: Analyze
|
name: analyze
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
actions: read
|
actions: read
|
||||||
@ -42,12 +42,15 @@ jobs:
|
|||||||
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
|
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
|
- name: setup
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: 1.17
|
||||||
# Initializes the CodeQL tools for scanning.
|
# Initializes the CodeQL tools for scanning.
|
||||||
- name: Initialize CodeQL
|
- name: init
|
||||||
uses: github/codeql-action/init@v1
|
uses: github/codeql-action/init@v2
|
||||||
with:
|
with:
|
||||||
languages: ${{ matrix.language }}
|
languages: ${{ matrix.language }}
|
||||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||||
@ -57,8 +60,8 @@ jobs:
|
|||||||
|
|
||||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||||
# If this step fails, then you should remove it and run the build manually (see below)
|
# If this step fails, then you should remove it and run the build manually (see below)
|
||||||
- name: Autobuild
|
- name: autobuild
|
||||||
uses: github/codeql-action/autobuild@v1
|
uses: github/codeql-action/autobuild@v2
|
||||||
|
|
||||||
# ℹ️ Command-line programs to run using the OS shell.
|
# ℹ️ Command-line programs to run using the OS shell.
|
||||||
# 📚 https://git.io/JvXDl
|
# 📚 https://git.io/JvXDl
|
||||||
@ -71,5 +74,5 @@ jobs:
|
|||||||
# make bootstrap
|
# make bootstrap
|
||||||
# make release
|
# make release
|
||||||
|
|
||||||
- name: Perform CodeQL Analysis
|
- name: analyze
|
||||||
uses: github/codeql-action/analyze@v1
|
uses: github/codeql-action/analyze@v2
|
||||||
|
73
.github/workflows/dependabot-automerge.yml
vendored
73
.github/workflows/dependabot-automerge.yml
vendored
@ -1,66 +1,27 @@
|
|||||||
name: "prautomerge"
|
name: "dependabot-automerge"
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_run:
|
pull_request_target:
|
||||||
workflows: ["prbuild"]
|
types: [assigned, opened, synchronize, reopened]
|
||||||
types:
|
|
||||||
- completed
|
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
|
contents: write
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
Dependabot-Automerge:
|
automerge:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
# Contains workaround to execute if dependabot updates the PR by checking for the base branch in the linked PR
|
if: github.actor == 'dependabot[bot]'
|
||||||
# The the github.event.workflow_run.event value is 'push' and not 'pull_request'
|
|
||||||
# dont work with multiple workflows when last returns success
|
|
||||||
if: >-
|
|
||||||
github.event.workflow_run.conclusion == 'success'
|
|
||||||
&& github.actor == 'dependabot[bot]'
|
|
||||||
&& github.event.sender.login == 'dependabot[bot]'
|
|
||||||
&& github.event.sender.type == 'Bot'
|
|
||||||
&& (github.event.workflow_run.event == 'pull_request'
|
|
||||||
|| (github.event.workflow_run.event == 'push' && github.event.workflow_run.pull_requests[0].base.ref == github.event.repository.default_branch ))
|
|
||||||
steps:
|
steps:
|
||||||
- name: Approve Changes and Merge changes if label 'dependencies' is set
|
- name: metadata
|
||||||
uses: actions/github-script@v5
|
id: metadata
|
||||||
|
uses: dependabot/fetch-metadata@v1.3.6
|
||||||
with:
|
with:
|
||||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
github-token: "${{ secrets.TOKEN }}"
|
||||||
script: |
|
- name: merge
|
||||||
console.log(context.payload.workflow_run);
|
id: merge
|
||||||
|
if: ${{contains(steps.metadata.outputs.dependency-names, 'go.unistack.org')}}
|
||||||
var labelNames = await github.paginate(
|
run: gh pr merge --auto --merge "$PR_URL"
|
||||||
github.issues.listLabelsOnIssue,
|
env:
|
||||||
{
|
PR_URL: ${{github.event.pull_request.html_url}}
|
||||||
repo: context.repo.repo,
|
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
||||||
owner: context.repo.owner,
|
|
||||||
issue_number: context.payload.workflow_run.pull_requests[0].number,
|
|
||||||
},
|
|
||||||
(response) => response.data.map(
|
|
||||||
(label) => label.name
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
console.log(labelNames);
|
|
||||||
|
|
||||||
if (labelNames.includes('dependencies')) {
|
|
||||||
console.log('Found label');
|
|
||||||
|
|
||||||
await github.pulls.createReview({
|
|
||||||
repo: context.repo.repo,
|
|
||||||
owner: context.repo.owner,
|
|
||||||
pull_number: context.payload.workflow_run.pull_requests[0].number,
|
|
||||||
event: 'APPROVE'
|
|
||||||
});
|
|
||||||
console.log('Approved PR');
|
|
||||||
|
|
||||||
await github.pulls.merge({
|
|
||||||
repo: context.repo.repo,
|
|
||||||
owner: context.repo.owner,
|
|
||||||
pull_number: context.payload.workflow_run.pull_requests[0].number,
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('Merged PR');
|
|
||||||
}
|
|
||||||
|
13
.github/workflows/pr.yml
vendored
13
.github/workflows/pr.yml
vendored
@ -3,19 +3,20 @@ on:
|
|||||||
pull_request:
|
pull_request:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
|
- v3
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
name: test
|
name: test
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: setup
|
- name: setup
|
||||||
uses: actions/setup-go@v2
|
uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
go-version: 1.16
|
go-version: 1.17
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
- name: cache
|
- name: cache
|
||||||
uses: actions/cache@v2
|
uses: actions/cache@v3
|
||||||
with:
|
with:
|
||||||
path: ~/go/pkg/mod
|
path: ~/go/pkg/mod
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
@ -31,9 +32,9 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
- name: lint
|
- name: lint
|
||||||
uses: golangci/golangci-lint-action@v2
|
uses: golangci/golangci-lint-action@v3.4.0
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||||
|
17
chi.go
17
chi.go
@ -4,9 +4,7 @@ import (
|
|||||||
"google.golang.org/protobuf/compiler/protogen"
|
"google.golang.org/protobuf/compiler/protogen"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var chiPackageFiles map[protogen.GoPackageName]struct{}
|
||||||
chiPackageFiles map[protogen.GoPackageName]struct{}
|
|
||||||
)
|
|
||||||
|
|
||||||
func (g *Generator) chiGenerate(component string, plugin *protogen.Plugin) error {
|
func (g *Generator) chiGenerate(component string, plugin *protogen.Plugin) error {
|
||||||
chiPackageFiles = make(map[protogen.GoPackageName]struct{})
|
chiPackageFiles = make(map[protogen.GoPackageName]struct{})
|
||||||
@ -43,7 +41,6 @@ func (g *Generator) chiGenerate(component string, plugin *protogen.Plugin) error
|
|||||||
gfile.Import(stringsPackage)
|
gfile.Import(stringsPackage)
|
||||||
gfile.Import(chiPackage)
|
gfile.Import(chiPackage)
|
||||||
gfile.Import(chiMiddlewarePackage)
|
gfile.Import(chiMiddlewarePackage)
|
||||||
gfile.Import(microApiPackage)
|
|
||||||
|
|
||||||
gfile.P("type routeKey struct{}")
|
gfile.P("type routeKey struct{}")
|
||||||
|
|
||||||
@ -52,17 +49,17 @@ func (g *Generator) chiGenerate(component string, plugin *protogen.Plugin) error
|
|||||||
gfile.P("return value, ok")
|
gfile.P("return value, ok")
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
gfile.P()
|
gfile.P()
|
||||||
gfile.P("func RegisterHandlers(r *", chiPackage.Ident("Mux"), ", h interface{}, eps []*", microApiPackage.Ident("Endpoint"), ") error {")
|
gfile.P("func RegisterHandlers(r *", chiPackage.Ident("Mux"), ", h interface{}, eps []", microServerHttpPackage.Ident("EndpointMetadata"), ") error {")
|
||||||
gfile.P("v := ", reflectPackage.Ident("ValueOf"), "(h)")
|
gfile.P("v := ", reflectPackage.Ident("ValueOf"), "(h)")
|
||||||
gfile.P("if v.NumMethod() < 1 {")
|
gfile.P("if v.NumMethod() < 1 {")
|
||||||
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("handler has no methods: %T", h)`)
|
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("handler has no methods: %T", h)`)
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
gfile.P("for _, ep := range eps {")
|
gfile.P("for _, ep := range eps {")
|
||||||
gfile.P(`idx := `, stringsPackage.Ident("Index"), `(ep.Name, ".")`)
|
gfile.P(`idx := `, stringsPackage.Ident("Index"), `(ep.Name, ".")`)
|
||||||
gfile.P("if idx < 1 || len(ep.Name) <= idx {")
|
gfile.P(`if idx < 1 || len(ep.Name) <= idx {`)
|
||||||
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid `, microApiPackage.Ident("Endpoint"), ` name: %s", ep.Name)`)
|
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid endpoint name: %s", ep.Name)`)
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
gfile.P("name := ep.Name[idx+1:]")
|
gfile.P(`name := ep.Name[idx+1:]`)
|
||||||
gfile.P("m := v.MethodByName(name)")
|
gfile.P("m := v.MethodByName(name)")
|
||||||
gfile.P("if !m.IsValid() || m.IsZero() {")
|
gfile.P("if !m.IsValid() || m.IsZero() {")
|
||||||
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid handler, method %s not found", name)`)
|
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid handler, method %s not found", name)`)
|
||||||
@ -71,9 +68,7 @@ func (g *Generator) chiGenerate(component string, plugin *protogen.Plugin) error
|
|||||||
gfile.P("if !ok {")
|
gfile.P("if !ok {")
|
||||||
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid handler: %#+v", m.Interface())`)
|
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid handler: %#+v", m.Interface())`)
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
gfile.P("for _, method := range ep.Method {")
|
gfile.P("r.With(", chiMiddlewarePackage.Ident("WithValue"), `(routeKey{}, ep.Name)).MethodFunc(ep.Method, ep.Path, rh)`)
|
||||||
gfile.P("r.With(", chiMiddlewarePackage.Ident("WithValue"), "(routeKey{}, ep.Name)).MethodFunc(method, ep.Path[0], rh)")
|
|
||||||
gfile.P("}")
|
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
gfile.P("return nil")
|
gfile.P("return nil")
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
|
@ -6,32 +6,28 @@ option go_package = "github.com/unistack-org/protoc-gen-go-micro/v3/example;exam
|
|||||||
|
|
||||||
import "tag/tag.proto";
|
import "tag/tag.proto";
|
||||||
import "api/annotations.proto";
|
import "api/annotations.proto";
|
||||||
import "openapiv2/annotations.proto";
|
import "openapiv3/annotations.proto";
|
||||||
import "google/protobuf/wrappers.proto";
|
//import "google/protobuf/wrappers.proto";
|
||||||
|
import "graphql/graphql.proto";
|
||||||
|
|
||||||
service Example {
|
service Example {
|
||||||
rpc Call(CallReq) returns (CallRsp) {
|
rpc Call(CallReq) returns (CallRsp) {
|
||||||
|
option (micro.graphql.rpc) = {type: QUERY};
|
||||||
option (micro.openapiv3.openapiv3_operation) = {
|
option (micro.openapiv3.openapiv3_operation) = {
|
||||||
operation_id: "Call";
|
operation_id: "Call";
|
||||||
responses: {
|
responses: {
|
||||||
key: "default";
|
default: {
|
||||||
value: {
|
reference: {_ref: ".example.Error"};
|
||||||
description: "Error response";
|
};
|
||||||
schema: {
|
};
|
||||||
json_schema: {
|
|
||||||
ref: ".example.Error";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
option (micro.api.http) = { post: "/v1/example/call/{name}"; body: "*"; };
|
option (micro.api.http) = { post: "/v1/example/call/{name}"; body: "*"; };
|
||||||
option (micro.api.micro_method) = { timeout: 5; };
|
option (micro.api.micro_method) = { timeout: "5s"; };
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
message CallReq {
|
message CallReq {
|
||||||
string name = 1 [(micro.tag.tags) = "xml:\",attr\"" ];
|
string name = 1 [(micro.graphql.field) = {required: true}];
|
||||||
string req = 2;
|
string req = 2;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
11
example/schema.graphql
Normal file
11
example/schema.graphql
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
directive @Example on FIELD_DEFINITION
|
||||||
|
input CallReqInput {
|
||||||
|
name: String!
|
||||||
|
req: String
|
||||||
|
}
|
||||||
|
type CallRsp {
|
||||||
|
rsp: String
|
||||||
|
}
|
||||||
|
type Query {
|
||||||
|
exampleCall(in: CallReqInput): CallRsp
|
||||||
|
}
|
24
fiealaligment.go
Normal file
24
fiealaligment.go
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"golang.org/x/tools/go/analysis/passes/fieldalignment"
|
||||||
|
"golang.org/x/tools/go/analysis/singlechecker"
|
||||||
|
"google.golang.org/protobuf/compiler/protogen"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (g *Generator) fieldAlign(plugin *protogen.Plugin) error {
|
||||||
|
if !g.fieldaligment {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("%v\n", []string{"fieldalignment", "-fix", g.tagPath})
|
||||||
|
origArgs := os.Args
|
||||||
|
os.Args = []string{"fieldalignment", "-fix", g.tagPath}
|
||||||
|
singlechecker.Main(fieldalignment.Analyzer)
|
||||||
|
os.Args = origArgs
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
3
generate.go
Normal file
3
generate.go
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
//go:generate sh -xc "protoc -I./example -I. -I$(go list -f '{{ .Dir }}' -m go.unistack.org/micro-proto/v3) --go-micro_out=components=graphqls,graphql_file=./schema.graphql:./example example/example.proto"
|
23
go.mod
23
go.mod
@ -1,13 +1,24 @@
|
|||||||
module go.unistack.org/protoc-gen-go-micro/v3
|
module go.unistack.org/protoc-gen-go-micro/v3
|
||||||
|
|
||||||
go 1.16
|
go 1.20
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/danielvladco/go-proto-gql v0.10.0
|
||||||
github.com/fatih/structtag v1.2.0
|
github.com/fatih/structtag v1.2.0
|
||||||
go.unistack.org/micro-proto/v3 v3.1.0
|
github.com/jhump/protoreflect v1.7.1
|
||||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
github.com/vektah/gqlparser/v2 v2.5.1
|
||||||
google.golang.org/protobuf v1.27.1
|
go.unistack.org/micro-proto/v3 v3.4.1
|
||||||
|
golang.org/x/tools v0.11.0
|
||||||
|
google.golang.org/protobuf v1.28.1
|
||||||
)
|
)
|
||||||
|
|
||||||
//replace go.unistack.org/micro/v3 => ../micro
|
require (
|
||||||
//replace go.unistack.org/micro-proto => ../micro-proto
|
github.com/golang/protobuf v1.5.3 // indirect
|
||||||
|
github.com/google/gnostic v0.6.9 // indirect
|
||||||
|
github.com/google/go-cmp v0.5.9 // indirect
|
||||||
|
github.com/kr/text v0.2.0 // indirect
|
||||||
|
golang.org/x/mod v0.12.0 // indirect
|
||||||
|
golang.org/x/sys v0.10.0 // indirect
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
)
|
||||||
|
208
go.sum
208
go.sum
@ -1,13 +1,211 @@
|
|||||||
|
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||||
|
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||||
|
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||||
|
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
|
||||||
|
github.com/agnivade/levenshtein v1.0.1/go.mod h1:CURSv5d9Uaml+FovSIICkLbAUZ9S4RqaHDIsdSBg7lM=
|
||||||
|
github.com/agnivade/levenshtein v1.1.1 h1:QY8M92nrzkmr798gCo3kmMyqXFzdQVpxLlGPRBij0P8=
|
||||||
|
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=
|
||||||
|
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
|
||||||
|
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
|
||||||
|
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||||
|
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||||
|
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
|
||||||
|
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||||
|
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
||||||
|
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
|
||||||
|
github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
|
||||||
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
|
github.com/danielvladco/go-proto-gql v0.10.0 h1:4nNRzK12HQG/ufFbS13s5+P+H9nAXV3BAf0hlp6WOg0=
|
||||||
|
github.com/danielvladco/go-proto-gql v0.10.0/go.mod h1:wgwSqh7arC6TQldj7Dfq20oHmCUzhH87cfZvQWMwSjE=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE=
|
||||||
|
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||||
|
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||||
|
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||||
|
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
|
||||||
|
github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ=
|
||||||
|
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||||
github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4=
|
github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4=
|
||||||
github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
|
github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
|
||||||
|
github.com/flowstack/go-jsonschema v0.1.1/go.mod h1:yL7fNggx1o8rm9RlgXv7hTBWxdBM0rVwpMwimd3F3N0=
|
||||||
|
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
|
||||||
|
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||||
|
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||||
|
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
|
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
|
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
|
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||||
|
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||||
|
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||||
|
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
|
||||||
|
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||||
|
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||||
|
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
|
||||||
|
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||||
|
github.com/google/gnostic v0.6.9 h1:ZK/5VhkoX835RikCHpSUJV9a+S3e1zLh59YnyWeBW+0=
|
||||||
|
github.com/google/gnostic v0.6.9/go.mod h1:Nm8234We1lq6iB9OmlgNv3nH91XLLVZHCDayfA3xq+E=
|
||||||
|
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||||
|
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
|
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||||
|
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
|
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||||
go.unistack.org/micro-proto/v3 v3.1.0 h1:q39FwjFiRZn+Ux/tt+d3bJTmDtsQQWa+3SLYVo1vLfA=
|
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||||
go.unistack.org/micro-proto/v3 v3.1.0/go.mod h1:DpRhYCBXlmSJ/AAXTmntvlh7kQkYU6eFvlmYAx4BQS8=
|
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
|
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
|
||||||
|
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/gordonklaus/ineffassign v0.0.0-20200309095847-7953dde2c7bf/go.mod h1:cuNKsD1zp2v6XfE/orVX2QE1LC+i254ceGcVeDT3pTU=
|
||||||
|
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
|
||||||
|
github.com/jhump/protoreflect v1.7.1 h1:dU3rf2wv1WHvC7mSGYfOaciUAFf5idu6FdC3uZIOlP0=
|
||||||
|
github.com/jhump/protoreflect v1.7.1/go.mod h1:RZkzh7Hi9J7qT/sPlWnJ/UwZqCJvciFxKDA0UCeltSM=
|
||||||
|
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||||
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
|
github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||||
|
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
|
||||||
|
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||||
|
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||||
|
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
|
github.com/nishanths/predeclared v0.0.0-20200524104333-86fad755b4d3/go.mod h1:nt3d53pc1VYcphSCIaYAJtnPYnr3Zyn8fMq2wvPGPso=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||||
|
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
|
||||||
|
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||||
|
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
|
||||||
|
github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ=
|
||||||
|
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
|
||||||
|
github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
|
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
|
||||||
|
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||||
|
github.com/vektah/gqlparser/v2 v2.5.1 h1:ZGu+bquAY23jsxDRcYpWjttRZrUz07LbiY77gUOHcr4=
|
||||||
|
github.com/vektah/gqlparser/v2 v2.5.1/go.mod h1:mPgqFBu/woKTVYWyNk8cO3kh4S/f4aRFZrvOnp3hmCs=
|
||||||
|
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
|
||||||
|
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
|
||||||
|
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
|
||||||
|
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
|
go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
|
||||||
|
go.unistack.org/micro-proto/v3 v3.4.1 h1:UTjLSRz2YZuaHk9iSlVqqsA50JQNAEK2ZFboGqtEa9Q=
|
||||||
|
go.unistack.org/micro-proto/v3 v3.4.1/go.mod h1:okx/cnOhzuCX0ggl/vToatbCupi0O44diiiLLsZ93Zo=
|
||||||
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
|
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
|
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
|
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||||
|
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||||
|
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||||
|
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||||
|
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
|
||||||
|
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||||
|
golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc=
|
||||||
|
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
|
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
|
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||||
|
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||||
|
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
|
golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50=
|
||||||
|
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||||
|
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||||
|
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E=
|
||||||
|
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA=
|
||||||
|
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||||
|
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||||
|
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||||
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.0.0-20200522201501-cb1345f3a375/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
|
||||||
|
golang.org/x/tools v0.11.0 h1:EMCa6U9S2LtZXLAMoWiR/R8dAQFRqbAitmbJ2UKhoi8=
|
||||||
|
golang.org/x/tools v0.11.0/go.mod h1:anzJrxPjNtfgiYQYirP2CPGzGLxrH2u2QBhn6Bf3qY8=
|
||||||
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
|
||||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||||
|
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||||
|
google.golang.org/genproto v0.0.0-20170818010345-ee236bd376b0/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||||
|
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||||
|
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
||||||
|
google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
|
||||||
|
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
|
||||||
|
google.golang.org/genproto v0.0.0-20220107163113-42d7afdf6368 h1:Et6SkiuvnBn+SgrSYXs/BrUpGB4mbdwt4R3vaPIlicA=
|
||||||
|
google.golang.org/genproto v0.0.0-20220107163113-42d7afdf6368/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc=
|
||||||
|
google.golang.org/grpc v1.8.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=
|
||||||
|
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||||
|
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
|
||||||
|
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
|
||||||
|
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
|
||||||
|
google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0=
|
||||||
|
google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU=
|
||||||
|
google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34=
|
||||||
|
google.golang.org/grpc v1.51.0 h1:E1eGv1FTqoLIdnBCZufiSHgKjlqG6fKFf6pPWtMTh8U=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||||
|
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||||
|
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||||
|
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||||
|
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||||
|
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||||
|
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||||
|
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
|
||||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||||
google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ=
|
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||||
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||||
|
google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=
|
||||||
|
google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||||
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
|
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
|
honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
|
||||||
|
15
gorilla.go
15
gorilla.go
@ -4,9 +4,7 @@ import (
|
|||||||
"google.golang.org/protobuf/compiler/protogen"
|
"google.golang.org/protobuf/compiler/protogen"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var gorillaPackageFiles map[protogen.GoPackageName]struct{}
|
||||||
gorillaPackageFiles map[protogen.GoPackageName]struct{}
|
|
||||||
)
|
|
||||||
|
|
||||||
func (g *Generator) gorillaGenerate(component string, plugin *protogen.Plugin) error {
|
func (g *Generator) gorillaGenerate(component string, plugin *protogen.Plugin) error {
|
||||||
gorillaPackageFiles = make(map[protogen.GoPackageName]struct{})
|
gorillaPackageFiles = make(map[protogen.GoPackageName]struct{})
|
||||||
@ -40,20 +38,19 @@ func (g *Generator) gorillaGenerate(component string, plugin *protogen.Plugin) e
|
|||||||
gfile.Import(httpPackage)
|
gfile.Import(httpPackage)
|
||||||
gfile.Import(reflectPackage)
|
gfile.Import(reflectPackage)
|
||||||
gfile.Import(stringsPackage)
|
gfile.Import(stringsPackage)
|
||||||
gfile.Import(microApiPackage)
|
|
||||||
gfile.Import(gorillaMuxPackage)
|
gfile.Import(gorillaMuxPackage)
|
||||||
|
|
||||||
gfile.P("func RegisterHandlers(r *", gorillaMuxPackage.Ident("Router"), ", h interface{}, eps []*", microApiPackage.Ident("Endpoint"), ") error {")
|
gfile.P("func RegisterHandlers(r *", gorillaMuxPackage.Ident("Router"), ", h interface{}, eps []", microServerHttpPackage.Ident("EndpointMetadata"), ") error {")
|
||||||
gfile.P("v := ", reflectPackage.Ident("ValueOf"), "(h)")
|
gfile.P("v := ", reflectPackage.Ident("ValueOf"), "(h)")
|
||||||
gfile.P("if v.NumMethod() < 1 {")
|
gfile.P("if v.NumMethod() < 1 {")
|
||||||
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("handler has no methods: %T", h)`)
|
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("handler has no methods: %T", h)`)
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
gfile.P("for _, ep := range eps {")
|
gfile.P("for _, ep := range eps {")
|
||||||
gfile.P(`idx := `, stringsPackage.Ident("Index"), `(ep.Name, ".")`)
|
gfile.P(`idx := `, stringsPackage.Ident("Index"), `(ep.Name, ".")`)
|
||||||
gfile.P("if idx < 1 || len(ep.Name) <= idx {")
|
gfile.P(`if idx < 1 || len(ep.Name) <= idx {`)
|
||||||
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid `, microApiPackage.Ident("Endpoint"), ` name: %s", ep.Name)`)
|
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid endpoint name: %s", ep.Name)`)
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
gfile.P("name := ep.Name[idx+1:]")
|
gfile.P(`name := ep.Name[idx+1:]`)
|
||||||
gfile.P("m := v.MethodByName(name)")
|
gfile.P("m := v.MethodByName(name)")
|
||||||
gfile.P("if !m.IsValid() || m.IsZero() {")
|
gfile.P("if !m.IsValid() || m.IsZero() {")
|
||||||
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid handler, method %s not found", name)`)
|
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid handler, method %s not found", name)`)
|
||||||
@ -62,7 +59,7 @@ func (g *Generator) gorillaGenerate(component string, plugin *protogen.Plugin) e
|
|||||||
gfile.P("if !ok {")
|
gfile.P("if !ok {")
|
||||||
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid handler: %#+v", m.Interface())`)
|
gfile.P(`return `, fmtPackage.Ident("Errorf"), `("invalid handler: %#+v", m.Interface())`)
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
gfile.P("r.HandleFunc(ep.Path[0], rh).Methods(ep.Method...).Name(ep.Name)")
|
gfile.P(`r.HandleFunc(ep.Path, rh).Methods(ep.Method).Name(ep.Name)`)
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
gfile.P("return nil")
|
gfile.P("return nil")
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
|
9
graphql.go
Normal file
9
graphql.go
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"google.golang.org/protobuf/compiler/protogen"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (g *Generator) graphqlGenerate(plugin *protogen.Plugin) error {
|
||||||
|
return nil
|
||||||
|
}
|
32
graphql/callstack.go
Normal file
32
graphql/callstack.go
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
package generator
|
||||||
|
|
||||||
|
type Callstack interface {
|
||||||
|
Push(entry interface{})
|
||||||
|
Pop(entry interface{})
|
||||||
|
Has(entry interface{}) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCallstack() Callstack {
|
||||||
|
return &callstack{stack: make(map[interface{}]int), index: 0}
|
||||||
|
}
|
||||||
|
|
||||||
|
type callstack struct {
|
||||||
|
stack map[interface{}]int
|
||||||
|
sorted []string
|
||||||
|
index int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *callstack) Pop(entry interface{}) {
|
||||||
|
delete(c.stack, entry)
|
||||||
|
c.index--
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *callstack) Push(entry interface{}) {
|
||||||
|
c.stack[entry] = c.index
|
||||||
|
c.index++
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *callstack) Has(entry interface{}) bool {
|
||||||
|
_, ok := c.stack[entry]
|
||||||
|
return ok
|
||||||
|
}
|
77
graphql/descriptors.go
Normal file
77
graphql/descriptors.go
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
package generator
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/jhump/protoreflect/desc"
|
||||||
|
"github.com/vektah/gqlparser/v2/ast"
|
||||||
|
any "google.golang.org/protobuf/types/known/anypb"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ObjectDescriptor struct {
|
||||||
|
*ast.Definition
|
||||||
|
desc.Descriptor
|
||||||
|
|
||||||
|
types []*ObjectDescriptor
|
||||||
|
fields []*FieldDescriptor
|
||||||
|
fieldNames map[string]*FieldDescriptor
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *ObjectDescriptor) AsGraphql() *ast.Definition {
|
||||||
|
return o.Definition
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *ObjectDescriptor) uniqueName(f *desc.FieldDescriptor) string {
|
||||||
|
return strings.Title(f.GetName())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *ObjectDescriptor) IsInput() bool {
|
||||||
|
return o.Kind == ast.InputObject
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *ObjectDescriptor) GetFields() []*FieldDescriptor {
|
||||||
|
return o.fields
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *ObjectDescriptor) GetTypes() []*ObjectDescriptor {
|
||||||
|
return o.types
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *ObjectDescriptor) IsMessage() bool {
|
||||||
|
_, ok := o.Descriptor.(*desc.MessageDescriptor)
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// same isEmpty but for mortals
|
||||||
|
func IsEmpty(o *desc.MessageDescriptor) bool { return isEmpty(o, NewCallstack()) }
|
||||||
|
|
||||||
|
// make sure objects are fulled with all objects
|
||||||
|
func isEmpty(o *desc.MessageDescriptor, callstack Callstack) bool {
|
||||||
|
callstack.Push(o)
|
||||||
|
defer callstack.Pop(o)
|
||||||
|
|
||||||
|
if len(o.GetFields()) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, f := range o.GetFields() {
|
||||||
|
objType := f.GetMessageType()
|
||||||
|
if objType == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// check if the call stack already contains a reference to this type and prevent it from calling itself again
|
||||||
|
if callstack.Has(objType) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if !isEmpty(objType, callstack) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO maybe not compare by strings
|
||||||
|
func IsAny(o *desc.MessageDescriptor) bool {
|
||||||
|
return string((&any.Any{}).ProtoReflect().Descriptor().FullName()) == o.GetFullyQualifiedName()
|
||||||
|
}
|
761
graphql/generator.go
Normal file
761
graphql/generator.go
Normal file
@ -0,0 +1,761 @@
|
|||||||
|
package generator
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/jhump/protoreflect/desc"
|
||||||
|
"github.com/vektah/gqlparser/v2/ast"
|
||||||
|
"google.golang.org/protobuf/compiler/protogen"
|
||||||
|
descriptor "google.golang.org/protobuf/types/descriptorpb"
|
||||||
|
|
||||||
|
gqlpb "go.unistack.org/micro-proto/v3/graphql"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
fieldPrefix = "Field"
|
||||||
|
inputSuffix = "Input"
|
||||||
|
typeSep = "_"
|
||||||
|
packageSep = "."
|
||||||
|
anyTypeDescription = "Any is any json type"
|
||||||
|
scalarBytes = "Bytes"
|
||||||
|
goFieldDirective = "goField"
|
||||||
|
|
||||||
|
DefaultExtension = "graphql"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewSchemas(descs []*desc.FileDescriptor, mergeSchemas, genServiceDesc bool, plugin *protogen.Plugin) (schemas SchemaDescriptorList, err error) {
|
||||||
|
var files []*descriptor.FileDescriptorProto
|
||||||
|
for _, d := range descs {
|
||||||
|
files = append(files, d.AsFileDescriptorProto())
|
||||||
|
}
|
||||||
|
var goref GoRef
|
||||||
|
if plugin != nil {
|
||||||
|
goref, err = NewGoRef(plugin)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if mergeSchemas {
|
||||||
|
schema := NewSchemaDescriptor(genServiceDesc, goref)
|
||||||
|
for _, file := range descs {
|
||||||
|
err := generateFile(file, schema)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return []*SchemaDescriptor{schema}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, file := range descs {
|
||||||
|
schema := NewSchemaDescriptor(genServiceDesc, goref)
|
||||||
|
err := generateFile(file, schema)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
schemas = append(schemas, schema)
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateFile(file *desc.FileDescriptor, schema *SchemaDescriptor) error {
|
||||||
|
schema.FileDescriptors = append(schema.FileDescriptors, file)
|
||||||
|
|
||||||
|
for _, svc := range file.GetServices() {
|
||||||
|
svcOpts := GraphqlServiceOptions(svc.AsServiceDescriptorProto().GetOptions())
|
||||||
|
if svcOpts != nil && svcOpts.Ignore != nil && *svcOpts.Ignore {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, rpc := range svc.GetMethods() {
|
||||||
|
rpcOpts := GraphqlMethodOptions(rpc.AsMethodDescriptorProto().GetOptions())
|
||||||
|
if rpcOpts != nil && rpcOpts.Ignore != nil && *rpcOpts.Ignore {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
in, err := schema.CreateObjects(rpc.GetInputType(), true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := schema.CreateObjects(rpc.GetOutputType(), false)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if rpc.IsServerStreaming() && rpc.IsClientStreaming() {
|
||||||
|
schema.GetMutation().addMethod(svc, rpc, in, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
if rpc.IsServerStreaming() {
|
||||||
|
schema.GetSubscription().addMethod(svc, rpc, in, out)
|
||||||
|
} else {
|
||||||
|
switch GetRequestType(rpcOpts, svcOpts) {
|
||||||
|
case gqlpb.Type_QUERY:
|
||||||
|
schema.GetQuery().addMethod(svc, rpc, in, out)
|
||||||
|
default:
|
||||||
|
schema.GetMutation().addMethod(svc, rpc, in, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type SchemaDescriptorList []*SchemaDescriptor
|
||||||
|
|
||||||
|
func (s SchemaDescriptorList) AsGraphql() (astSchema []*ast.Schema) {
|
||||||
|
for _, ss := range s {
|
||||||
|
astSchema = append(astSchema, ss.AsGraphql())
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s SchemaDescriptorList) GetForDescriptor(file *protogen.File) *SchemaDescriptor {
|
||||||
|
for _, schema := range s {
|
||||||
|
for _, d := range schema.FileDescriptors {
|
||||||
|
if d.AsFileDescriptorProto() == file.Proto {
|
||||||
|
return schema
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSchemaDescriptor(genServiceDesc bool, goref GoRef) *SchemaDescriptor {
|
||||||
|
sd := &SchemaDescriptor{
|
||||||
|
Directives: map[string]*ast.DirectiveDefinition{},
|
||||||
|
reservedNames: map[string]desc.Descriptor{},
|
||||||
|
createdObjects: map[createdObjectKey]*ObjectDescriptor{},
|
||||||
|
generateServiceDescriptors: genServiceDesc,
|
||||||
|
goRef: goref,
|
||||||
|
}
|
||||||
|
for _, name := range graphqlReservedNames {
|
||||||
|
sd.reservedNames[name] = nil
|
||||||
|
}
|
||||||
|
return sd
|
||||||
|
}
|
||||||
|
|
||||||
|
type SchemaDescriptor struct {
|
||||||
|
Directives map[string]*ast.DirectiveDefinition
|
||||||
|
FileDescriptors []*desc.FileDescriptor
|
||||||
|
|
||||||
|
files []*desc.FileDescriptor
|
||||||
|
|
||||||
|
query *RootDefinition
|
||||||
|
mutation *RootDefinition
|
||||||
|
subscription *RootDefinition
|
||||||
|
|
||||||
|
objects []*ObjectDescriptor
|
||||||
|
|
||||||
|
reservedNames map[string]desc.Descriptor
|
||||||
|
createdObjects map[createdObjectKey]*ObjectDescriptor
|
||||||
|
|
||||||
|
generateServiceDescriptors bool
|
||||||
|
|
||||||
|
goRef GoRef
|
||||||
|
}
|
||||||
|
|
||||||
|
type createdObjectKey struct {
|
||||||
|
desc desc.Descriptor
|
||||||
|
input bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SchemaDescriptor) AsGraphql() *ast.Schema {
|
||||||
|
queryDef := *s.GetQuery().Definition
|
||||||
|
mutationDef := *s.GetMutation().Definition
|
||||||
|
subscriptionsDef := *s.GetSubscription().Definition
|
||||||
|
schema := &ast.Schema{Types: map[string]*ast.Definition{}, Directives: s.Directives}
|
||||||
|
schema.Query = &queryDef
|
||||||
|
schema.Types["Query"] = &queryDef
|
||||||
|
if s.query.methods == nil {
|
||||||
|
schema.Query.Fields = append(schema.Query.Fields, &ast.FieldDefinition{
|
||||||
|
Name: "dummy",
|
||||||
|
Type: ast.NamedType("Boolean", &ast.Position{}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if s.mutation.methods != nil {
|
||||||
|
schema.Mutation = &mutationDef
|
||||||
|
schema.Types["Mutation"] = &mutationDef
|
||||||
|
}
|
||||||
|
if s.subscription.methods != nil {
|
||||||
|
schema.Subscription = &subscriptionsDef
|
||||||
|
schema.Types["Subscription"] = &subscriptionsDef
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, o := range s.objects {
|
||||||
|
def := o.AsGraphql()
|
||||||
|
schema.Types[def.Name] = def
|
||||||
|
}
|
||||||
|
return schema
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SchemaDescriptor) Objects() []*ObjectDescriptor {
|
||||||
|
return s.objects
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SchemaDescriptor) GetMutation() *RootDefinition {
|
||||||
|
if s.mutation == nil {
|
||||||
|
s.mutation = NewRootDefinition(Mutation, s)
|
||||||
|
}
|
||||||
|
return s.mutation
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SchemaDescriptor) GetSubscription() *RootDefinition {
|
||||||
|
if s.subscription == nil {
|
||||||
|
s.subscription = NewRootDefinition(Subscription, s)
|
||||||
|
}
|
||||||
|
return s.subscription
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SchemaDescriptor) GetQuery() *RootDefinition {
|
||||||
|
if s.query == nil {
|
||||||
|
s.query = NewRootDefinition(Query, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.query
|
||||||
|
}
|
||||||
|
|
||||||
|
// make name be unique
|
||||||
|
// just create a map and register every name
|
||||||
|
func (s *SchemaDescriptor) uniqueName(d desc.Descriptor, input bool) (name string) {
|
||||||
|
var collisionPrefix string
|
||||||
|
var suffix string
|
||||||
|
if _, ok := d.(*desc.MessageDescriptor); input && ok {
|
||||||
|
suffix = inputSuffix
|
||||||
|
}
|
||||||
|
name = strings.Title(CamelCaseSlice(strings.Split(strings.TrimPrefix(d.GetFullyQualifiedName(), d.GetFile().GetPackage()+packageSep), packageSep)) + suffix)
|
||||||
|
|
||||||
|
if _, ok := d.(*desc.FieldDescriptor); ok {
|
||||||
|
collisionPrefix = fieldPrefix
|
||||||
|
name = CamelCaseSlice(strings.Split(strings.Trim(d.GetParent().GetName()+packageSep+strings.Title(d.GetName()), packageSep), packageSep))
|
||||||
|
} else {
|
||||||
|
collisionPrefix = CamelCaseSlice(strings.Split(d.GetFile().GetPackage(), packageSep))
|
||||||
|
}
|
||||||
|
|
||||||
|
originalName := name
|
||||||
|
for uniqueSuffix := 0; ; uniqueSuffix++ {
|
||||||
|
d2, ok := s.reservedNames[name]
|
||||||
|
if !ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if d2 == d {
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
if uniqueSuffix == 0 {
|
||||||
|
name = collisionPrefix + typeSep + originalName
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
name = collisionPrefix + typeSep + originalName + strconv.Itoa(uniqueSuffix)
|
||||||
|
}
|
||||||
|
|
||||||
|
s.reservedNames[name] = d
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SchemaDescriptor) CreateObjects(d desc.Descriptor, input bool) (obj *ObjectDescriptor, err error) {
|
||||||
|
// the case if trying to resolve a primitive as a object. In this case we just return nil
|
||||||
|
if d == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if obj, ok := s.createdObjects[createdObjectKey{d, input}]; ok {
|
||||||
|
return obj, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
obj = &ObjectDescriptor{
|
||||||
|
Definition: &ast.Definition{
|
||||||
|
Description: getDescription(d),
|
||||||
|
Name: s.uniqueName(d, input),
|
||||||
|
Position: &ast.Position{},
|
||||||
|
},
|
||||||
|
Descriptor: d,
|
||||||
|
}
|
||||||
|
|
||||||
|
s.createdObjects[createdObjectKey{d, input}] = obj
|
||||||
|
|
||||||
|
switch dd := d.(type) {
|
||||||
|
case *desc.MessageDescriptor:
|
||||||
|
if IsEmpty(dd) {
|
||||||
|
return obj, nil
|
||||||
|
}
|
||||||
|
if IsAny(dd) {
|
||||||
|
// TODO find a better way to handle any types
|
||||||
|
delete(s.createdObjects, createdObjectKey{d, input})
|
||||||
|
any := s.createScalar(s.uniqueName(dd, false), anyTypeDescription)
|
||||||
|
return any, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
kind := ast.Object
|
||||||
|
if input {
|
||||||
|
kind = ast.InputObject
|
||||||
|
}
|
||||||
|
fields := FieldDescriptorList{}
|
||||||
|
outputOneofRegistrar := map[*desc.OneOfDescriptor]struct{}{}
|
||||||
|
|
||||||
|
for _, df := range dd.GetFields() {
|
||||||
|
fieldOpts := GraphqlFieldOptions(df.AsFieldDescriptorProto().GetOptions())
|
||||||
|
if fieldOpts != nil && fieldOpts.Ignore != nil && *fieldOpts.Ignore {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var fieldDirective []*ast.Directive
|
||||||
|
if df.GetType() == descriptor.FieldDescriptorProto_TYPE_MESSAGE && IsEmpty(df.GetMessageType()) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Internally `optional` fields are represented as a oneof, and as such should be skipped.
|
||||||
|
if oneof := df.GetOneOf(); oneof != nil && !df.AsFieldDescriptorProto().GetProto3Optional() {
|
||||||
|
opts := GraphqlOneofOptions(oneof.AsOneofDescriptorProto().GetOptions())
|
||||||
|
if opts.GetIgnore() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !input {
|
||||||
|
if _, ok := outputOneofRegistrar[oneof]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
outputOneofRegistrar[oneof] = struct{}{}
|
||||||
|
field, err := s.createUnion(oneof)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
fields = append(fields, field)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// create oneofs as directives for input objects
|
||||||
|
directive := &ast.DirectiveDefinition{
|
||||||
|
Description: getDescription(oneof),
|
||||||
|
Name: s.uniqueName(oneof, input),
|
||||||
|
Locations: []ast.DirectiveLocation{ast.LocationInputFieldDefinition},
|
||||||
|
Position: &ast.Position{Src: &ast.Source{}},
|
||||||
|
}
|
||||||
|
s.Directives[directive.Name] = directive
|
||||||
|
fieldDirective = append(fieldDirective, &ast.Directive{
|
||||||
|
Name: directive.Name,
|
||||||
|
Position: &ast.Position{Src: &ast.Source{}},
|
||||||
|
// ParentDefinition: obj.Definition, TODO
|
||||||
|
Definition: directive,
|
||||||
|
Location: ast.LocationInputFieldDefinition,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fieldObj, err := s.CreateObjects(resolveFieldType(df), input)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if fieldObj == nil && df.GetMessageType() != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
f, err := s.createField(df, fieldObj)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
f.Directives = append(f.Directives, fieldDirective...)
|
||||||
|
fields = append(fields, f)
|
||||||
|
}
|
||||||
|
|
||||||
|
obj.Definition.Fields = fields.AsGraphql()
|
||||||
|
obj.Definition.Kind = kind
|
||||||
|
obj.fields = fields
|
||||||
|
case *desc.EnumDescriptor:
|
||||||
|
obj.Definition.Kind = ast.Enum
|
||||||
|
obj.Definition.EnumValues = enumValues(dd.GetValues())
|
||||||
|
default:
|
||||||
|
panic(fmt.Sprintf("received unexpected value %v of type %T", dd, dd))
|
||||||
|
}
|
||||||
|
|
||||||
|
s.objects = append(s.objects, obj)
|
||||||
|
return obj, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveFieldType(field *desc.FieldDescriptor) desc.Descriptor {
|
||||||
|
msgType := field.GetMessageType()
|
||||||
|
enumType := field.GetEnumType()
|
||||||
|
if msgType != nil {
|
||||||
|
return msgType
|
||||||
|
}
|
||||||
|
if enumType != nil {
|
||||||
|
return enumType
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func enumValues(evals []*desc.EnumValueDescriptor) (vlist ast.EnumValueList) {
|
||||||
|
for _, eval := range evals {
|
||||||
|
vlist = append(vlist, &ast.EnumValueDefinition{
|
||||||
|
Description: getDescription(eval),
|
||||||
|
Name: eval.GetName(),
|
||||||
|
Position: &ast.Position{},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return vlist
|
||||||
|
}
|
||||||
|
|
||||||
|
type FieldDescriptorList []*FieldDescriptor
|
||||||
|
|
||||||
|
func (fl FieldDescriptorList) AsGraphql() (dl []*ast.FieldDefinition) {
|
||||||
|
for _, f := range fl {
|
||||||
|
dl = append(dl, f.FieldDefinition)
|
||||||
|
}
|
||||||
|
return dl
|
||||||
|
}
|
||||||
|
|
||||||
|
type FieldDescriptor struct {
|
||||||
|
*ast.FieldDefinition
|
||||||
|
*desc.FieldDescriptor
|
||||||
|
|
||||||
|
typ *ObjectDescriptor
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FieldDescriptor) GetType() *ObjectDescriptor {
|
||||||
|
return f.typ
|
||||||
|
}
|
||||||
|
|
||||||
|
type MethodDescriptor struct {
|
||||||
|
*desc.ServiceDescriptor
|
||||||
|
*desc.MethodDescriptor
|
||||||
|
|
||||||
|
*ast.FieldDefinition
|
||||||
|
|
||||||
|
input *ObjectDescriptor
|
||||||
|
output *ObjectDescriptor
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MethodDescriptor) AsGraphql() *ast.FieldDefinition {
|
||||||
|
return m.FieldDefinition
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MethodDescriptor) GetInput() *ObjectDescriptor {
|
||||||
|
return m.input
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MethodDescriptor) GetOutput() *ObjectDescriptor {
|
||||||
|
return m.output
|
||||||
|
}
|
||||||
|
|
||||||
|
type RootDefinition struct {
|
||||||
|
*ast.Definition
|
||||||
|
|
||||||
|
Parent *SchemaDescriptor
|
||||||
|
|
||||||
|
methods []*MethodDescriptor
|
||||||
|
reservedNames map[string]ServiceAndMethod
|
||||||
|
}
|
||||||
|
|
||||||
|
type ServiceAndMethod struct {
|
||||||
|
svc *descriptor.ServiceDescriptorProto
|
||||||
|
rpc *descriptor.MethodDescriptorProto
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *RootDefinition) UniqueName(svc *descriptor.ServiceDescriptorProto, rpc *descriptor.MethodDescriptorProto) (name string) {
|
||||||
|
rpcOpts := GraphqlMethodOptions(rpc.GetOptions())
|
||||||
|
svcOpts := GraphqlServiceOptions(svc.GetOptions())
|
||||||
|
if rpcOpts != nil && rpcOpts.Name != nil {
|
||||||
|
name = *rpcOpts.Name
|
||||||
|
} else if svcOpts != nil && svcOpts.Name != nil {
|
||||||
|
if *svcOpts.Name == "" {
|
||||||
|
name = ToLowerFirst(rpc.GetName())
|
||||||
|
} else {
|
||||||
|
name = *svcOpts.Name + strings.Title(rpc.GetName())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
name = ToLowerFirst(svc.GetName()) + strings.Title(rpc.GetName())
|
||||||
|
}
|
||||||
|
|
||||||
|
originalName := name
|
||||||
|
for uniqueSuffix := 0; ; uniqueSuffix++ {
|
||||||
|
snm, ok := r.reservedNames[name]
|
||||||
|
if !ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if svc == snm.svc && snm.rpc == rpc {
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
name = originalName + strconv.Itoa(uniqueSuffix)
|
||||||
|
}
|
||||||
|
|
||||||
|
r.reservedNames[name] = ServiceAndMethod{svc, rpc}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *RootDefinition) Methods() []*MethodDescriptor {
|
||||||
|
return r.methods
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *RootDefinition) addMethod(svc *desc.ServiceDescriptor, rpc *desc.MethodDescriptor, in, out *ObjectDescriptor) {
|
||||||
|
var args ast.ArgumentDefinitionList
|
||||||
|
|
||||||
|
if in != nil && (in.Descriptor != nil && !IsEmpty(in.Descriptor.(*desc.MessageDescriptor)) || in.Definition.Kind == ast.Scalar) {
|
||||||
|
args = append(args, &ast.ArgumentDefinition{
|
||||||
|
Name: "in",
|
||||||
|
Type: ast.NamedType(in.Name, &ast.Position{}),
|
||||||
|
Position: &ast.Position{},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
objType := ast.NamedType("Boolean", &ast.Position{})
|
||||||
|
if out != nil && (out.Descriptor != nil && !IsEmpty(out.Descriptor.(*desc.MessageDescriptor)) || in.Definition.Kind == ast.Scalar) {
|
||||||
|
objType = ast.NamedType(out.Name, &ast.Position{})
|
||||||
|
}
|
||||||
|
|
||||||
|
svcDir := &ast.DirectiveDefinition{
|
||||||
|
Description: getDescription(svc),
|
||||||
|
Name: svc.GetName(),
|
||||||
|
Locations: []ast.DirectiveLocation{ast.LocationFieldDefinition},
|
||||||
|
Position: &ast.Position{Src: &ast.Source{}},
|
||||||
|
}
|
||||||
|
r.Parent.Directives[svcDir.Name] = svcDir
|
||||||
|
|
||||||
|
m := &MethodDescriptor{
|
||||||
|
ServiceDescriptor: svc,
|
||||||
|
MethodDescriptor: rpc,
|
||||||
|
FieldDefinition: &ast.FieldDefinition{
|
||||||
|
Description: getDescription(rpc),
|
||||||
|
Name: r.UniqueName(svc.AsServiceDescriptorProto(), rpc.AsMethodDescriptorProto()),
|
||||||
|
Arguments: args,
|
||||||
|
Type: objType,
|
||||||
|
Position: &ast.Position{},
|
||||||
|
},
|
||||||
|
input: in,
|
||||||
|
output: out,
|
||||||
|
}
|
||||||
|
if r.Parent.generateServiceDescriptors {
|
||||||
|
m.Directives = []*ast.Directive{{
|
||||||
|
Name: svcDir.Name,
|
||||||
|
Position: &ast.Position{},
|
||||||
|
Definition: svcDir,
|
||||||
|
Location: svcDir.Locations[0],
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
|
||||||
|
r.methods = append(r.methods, m)
|
||||||
|
// TODO maybe not do it here?
|
||||||
|
r.Definition.Fields = append(r.Definition.Fields, m.FieldDefinition)
|
||||||
|
}
|
||||||
|
|
||||||
|
type rootName string
|
||||||
|
|
||||||
|
const (
|
||||||
|
Mutation rootName = "Mutation"
|
||||||
|
Query rootName = "Query"
|
||||||
|
Subscription rootName = "Subscription"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewRootDefinition(name rootName, parent *SchemaDescriptor) *RootDefinition {
|
||||||
|
return &RootDefinition{Definition: &ast.Definition{
|
||||||
|
Kind: ast.Object,
|
||||||
|
Name: string(name),
|
||||||
|
Position: &ast.Position{},
|
||||||
|
}, Parent: parent, reservedNames: map[string]ServiceAndMethod{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getDescription(descs ...desc.Descriptor) string {
|
||||||
|
var description []string
|
||||||
|
for _, d := range descs {
|
||||||
|
info := d.GetSourceInfo()
|
||||||
|
if info == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if info.LeadingComments != nil {
|
||||||
|
description = append(description, *info.LeadingComments)
|
||||||
|
}
|
||||||
|
if info.TrailingComments != nil {
|
||||||
|
description = append(description, *info.TrailingComments)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return strings.Join(description, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SchemaDescriptor) createField(field *desc.FieldDescriptor, obj *ObjectDescriptor) (_ *FieldDescriptor, err error) {
|
||||||
|
fieldAst := &ast.FieldDefinition{
|
||||||
|
Description: getDescription(field),
|
||||||
|
Name: ToLowerFirst(CamelCase(field.GetName())),
|
||||||
|
Type: &ast.Type{Position: &ast.Position{}},
|
||||||
|
Position: &ast.Position{},
|
||||||
|
}
|
||||||
|
fieldOpts := GraphqlFieldOptions(field.AsFieldDescriptorProto().GetOptions())
|
||||||
|
if fieldOpts != nil && fieldOpts.Name != nil {
|
||||||
|
fieldAst.Name = *fieldOpts.Name
|
||||||
|
directive := &ast.DirectiveDefinition{
|
||||||
|
Name: goFieldDirective,
|
||||||
|
Arguments: []*ast.ArgumentDefinition{{
|
||||||
|
Name: "forceResolver",
|
||||||
|
Type: ast.NamedType("Boolean", &ast.Position{}),
|
||||||
|
Position: &ast.Position{},
|
||||||
|
}, {
|
||||||
|
Name: "name",
|
||||||
|
Type: ast.NamedType("String", &ast.Position{}),
|
||||||
|
Position: &ast.Position{},
|
||||||
|
}},
|
||||||
|
Locations: []ast.DirectiveLocation{ast.LocationInputFieldDefinition, ast.LocationFieldDefinition},
|
||||||
|
Position: &ast.Position{Src: &ast.Source{}},
|
||||||
|
}
|
||||||
|
s.Directives[directive.Name] = directive
|
||||||
|
if s.goRef != nil {
|
||||||
|
fieldAst.Directives = []*ast.Directive{{
|
||||||
|
Name: directive.Name,
|
||||||
|
Arguments: []*ast.Argument{{
|
||||||
|
Name: "name",
|
||||||
|
Value: &ast.Value{
|
||||||
|
Raw: s.goRef.FindGoField(field.GetFullyQualifiedName()).GoName,
|
||||||
|
Kind: ast.StringValue,
|
||||||
|
Position: &ast.Position{},
|
||||||
|
},
|
||||||
|
Position: &ast.Position{},
|
||||||
|
}},
|
||||||
|
Position: &ast.Position{},
|
||||||
|
// ParentDefinition: nil, TODO
|
||||||
|
Definition: directive,
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch field.GetType() {
|
||||||
|
case descriptor.FieldDescriptorProto_TYPE_DOUBLE,
|
||||||
|
descriptor.FieldDescriptorProto_TYPE_FLOAT:
|
||||||
|
fieldAst.Type.NamedType = ScalarFloat
|
||||||
|
|
||||||
|
case descriptor.FieldDescriptorProto_TYPE_BYTES:
|
||||||
|
scalar := s.createScalar(scalarBytes, "")
|
||||||
|
fieldAst.Type.NamedType = scalar.Name
|
||||||
|
|
||||||
|
case descriptor.FieldDescriptorProto_TYPE_INT64,
|
||||||
|
descriptor.FieldDescriptorProto_TYPE_SINT64,
|
||||||
|
descriptor.FieldDescriptorProto_TYPE_SFIXED64,
|
||||||
|
descriptor.FieldDescriptorProto_TYPE_INT32,
|
||||||
|
descriptor.FieldDescriptorProto_TYPE_SINT32,
|
||||||
|
descriptor.FieldDescriptorProto_TYPE_SFIXED32,
|
||||||
|
descriptor.FieldDescriptorProto_TYPE_UINT32,
|
||||||
|
descriptor.FieldDescriptorProto_TYPE_FIXED32,
|
||||||
|
descriptor.FieldDescriptorProto_TYPE_UINT64,
|
||||||
|
descriptor.FieldDescriptorProto_TYPE_FIXED64:
|
||||||
|
fieldAst.Type.NamedType = ScalarInt
|
||||||
|
|
||||||
|
case descriptor.FieldDescriptorProto_TYPE_BOOL:
|
||||||
|
fieldAst.Type.NamedType = ScalarBoolean
|
||||||
|
|
||||||
|
case descriptor.FieldDescriptorProto_TYPE_STRING:
|
||||||
|
fieldAst.Type.NamedType = ScalarString
|
||||||
|
|
||||||
|
case descriptor.FieldDescriptorProto_TYPE_GROUP:
|
||||||
|
return nil, fmt.Errorf("proto2 groups are not supported please use proto3 syntax")
|
||||||
|
|
||||||
|
case descriptor.FieldDescriptorProto_TYPE_ENUM:
|
||||||
|
fieldAst.Type.NamedType = obj.Name
|
||||||
|
|
||||||
|
case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
|
||||||
|
fieldAst.Type.NamedType = obj.Name
|
||||||
|
|
||||||
|
default:
|
||||||
|
panic("unknown proto field type")
|
||||||
|
}
|
||||||
|
|
||||||
|
if isRepeated(field) {
|
||||||
|
fieldAst.Type = ast.ListType(fieldAst.Type, &ast.Position{})
|
||||||
|
fieldAst.Type.Elem.NonNull = true
|
||||||
|
}
|
||||||
|
if isRequired(field) {
|
||||||
|
fieldAst.Type.NonNull = true
|
||||||
|
}
|
||||||
|
|
||||||
|
return &FieldDescriptor{
|
||||||
|
FieldDefinition: fieldAst,
|
||||||
|
FieldDescriptor: field,
|
||||||
|
typ: obj,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SchemaDescriptor) createScalar(name string, description string) *ObjectDescriptor {
|
||||||
|
obj := &ObjectDescriptor{
|
||||||
|
Definition: &ast.Definition{
|
||||||
|
Kind: ast.Scalar,
|
||||||
|
Description: description,
|
||||||
|
Name: name,
|
||||||
|
Position: &ast.Position{},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
s.objects = append(s.objects, obj)
|
||||||
|
return obj
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SchemaDescriptor) createUnion(oneof *desc.OneOfDescriptor) (*FieldDescriptor, error) {
|
||||||
|
var types []string
|
||||||
|
var objTypes []*ObjectDescriptor
|
||||||
|
for _, choice := range oneof.GetChoices() {
|
||||||
|
obj, err := s.CreateObjects(resolveFieldType(choice), false)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
f, err := s.createField(choice, obj)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
obj = &ObjectDescriptor{
|
||||||
|
Definition: &ast.Definition{
|
||||||
|
Kind: ast.Object,
|
||||||
|
Description: getDescription(f),
|
||||||
|
Name: s.uniqueName(choice, false),
|
||||||
|
Fields: ast.FieldList{f.FieldDefinition},
|
||||||
|
Position: &ast.Position{},
|
||||||
|
},
|
||||||
|
Descriptor: f,
|
||||||
|
fields: []*FieldDescriptor{f},
|
||||||
|
fieldNames: map[string]*FieldDescriptor{},
|
||||||
|
}
|
||||||
|
s.objects = append(s.objects, obj)
|
||||||
|
types = append(types, obj.Name)
|
||||||
|
objTypes = append(objTypes, obj)
|
||||||
|
}
|
||||||
|
obj := &ObjectDescriptor{
|
||||||
|
Definition: &ast.Definition{
|
||||||
|
Kind: ast.Union,
|
||||||
|
Description: getDescription(oneof),
|
||||||
|
Name: s.uniqueName(oneof, false),
|
||||||
|
Types: types,
|
||||||
|
Position: &ast.Position{},
|
||||||
|
},
|
||||||
|
Descriptor: oneof,
|
||||||
|
types: objTypes,
|
||||||
|
}
|
||||||
|
s.objects = append(s.objects, obj)
|
||||||
|
name := ToLowerFirst(CamelCase(oneof.GetName()))
|
||||||
|
opts := GraphqlOneofOptions(oneof.AsOneofDescriptorProto().GetOptions())
|
||||||
|
if opts.GetName() != "" {
|
||||||
|
name = opts.GetName()
|
||||||
|
}
|
||||||
|
return &FieldDescriptor{
|
||||||
|
FieldDefinition: &ast.FieldDefinition{
|
||||||
|
Description: getDescription(oneof),
|
||||||
|
Name: name,
|
||||||
|
Type: ast.NamedType(obj.Name, &ast.Position{}),
|
||||||
|
Position: &ast.Position{},
|
||||||
|
},
|
||||||
|
FieldDescriptor: nil,
|
||||||
|
typ: obj,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func isRepeated(field *desc.FieldDescriptor) bool {
|
||||||
|
return field.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED
|
||||||
|
}
|
||||||
|
|
||||||
|
func isRequired(field *desc.FieldDescriptor) bool {
|
||||||
|
if v := GraphqlFieldOptions(field.AsFieldDescriptorProto().GetOptions()); v != nil {
|
||||||
|
return v.GetRequired()
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
ScalarInt = "Int"
|
||||||
|
ScalarFloat = "Float"
|
||||||
|
ScalarString = "String"
|
||||||
|
ScalarBoolean = "Boolean"
|
||||||
|
ScalarID = "ID"
|
||||||
|
)
|
||||||
|
|
||||||
|
var graphqlReservedNames = []string{"__Directive", "__Type", "__Field", "__EnumValue", "__InputValue", "__Schema", "Int", "Float", "String", "Boolean", "ID"}
|
30
graphql/goreference.go
Normal file
30
graphql/goreference.go
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
package generator
|
||||||
|
|
||||||
|
import (
|
||||||
|
"google.golang.org/protobuf/compiler/protogen"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GoRef interface {
|
||||||
|
FindGoField(field string) *protogen.Field
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewGoRef(p *protogen.Plugin) (GoRef, error) {
|
||||||
|
return goRef{p}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type goRef struct {
|
||||||
|
*protogen.Plugin
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g goRef) FindGoField(field string) *protogen.Field {
|
||||||
|
for _, file := range g.Files {
|
||||||
|
for _, msg := range file.Messages {
|
||||||
|
for _, f := range msg.Fields {
|
||||||
|
if string(f.Desc.FullName()) == field {
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
139
graphql/registry.go
Normal file
139
graphql/registry.go
Normal file
@ -0,0 +1,139 @@
|
|||||||
|
package generator
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/jhump/protoreflect/desc"
|
||||||
|
"github.com/vektah/gqlparser/v2/ast"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Registry interface {
|
||||||
|
FindMethodByName(op ast.Operation, name string) *desc.MethodDescriptor
|
||||||
|
FindObjectByName(name string) *desc.MessageDescriptor
|
||||||
|
|
||||||
|
// FindObjectByFullyQualifiedName TODO maybe find a better way to get ast definition
|
||||||
|
FindObjectByFullyQualifiedName(fqn string) (*desc.MessageDescriptor, *ast.Definition)
|
||||||
|
|
||||||
|
// FindFieldByName given the proto Descriptor and the graphql field name get the the proto FieldDescriptor
|
||||||
|
FindFieldByName(msg desc.Descriptor, name string) *desc.FieldDescriptor
|
||||||
|
|
||||||
|
// FindUnionFieldByMessageFQNAndName given the proto Descriptor and the graphql field name get the the proto FieldDescriptor
|
||||||
|
FindUnionFieldByMessageFQNAndName(fqn, name string) *desc.FieldDescriptor
|
||||||
|
|
||||||
|
FindGraphqlFieldByProtoField(msg *ast.Definition, name string) *ast.FieldDefinition
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRegistry(files SchemaDescriptorList) Registry {
|
||||||
|
v := &repository{
|
||||||
|
mu: &sync.RWMutex{},
|
||||||
|
methodsByName: map[ast.Operation]map[string]*desc.MethodDescriptor{},
|
||||||
|
objectsByName: map[string]*desc.MessageDescriptor{},
|
||||||
|
objectsByFQN: map[string]*ObjectDescriptor{},
|
||||||
|
graphqlFieldsByName: map[desc.Descriptor]map[string]*desc.FieldDescriptor{},
|
||||||
|
graphqlUnionFieldsByName: map[string]map[string]*desc.FieldDescriptor{},
|
||||||
|
protoFieldsByName: map[*ast.Definition]map[string]*ast.FieldDefinition{},
|
||||||
|
}
|
||||||
|
for _, f := range files {
|
||||||
|
v.methodsByName[ast.Mutation] = map[string]*desc.MethodDescriptor{}
|
||||||
|
for _, m := range f.GetMutation().Methods() {
|
||||||
|
v.methodsByName[ast.Mutation][m.Name] = m.MethodDescriptor
|
||||||
|
}
|
||||||
|
v.methodsByName[ast.Query] = map[string]*desc.MethodDescriptor{}
|
||||||
|
for _, m := range f.GetQuery().Methods() {
|
||||||
|
v.methodsByName[ast.Query][m.Name] = m.MethodDescriptor
|
||||||
|
}
|
||||||
|
v.methodsByName[ast.Subscription] = map[string]*desc.MethodDescriptor{}
|
||||||
|
for _, m := range f.GetSubscription().Methods() {
|
||||||
|
v.methodsByName[ast.Subscription][m.Name] = m.MethodDescriptor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, f := range files {
|
||||||
|
for _, m := range f.Objects() {
|
||||||
|
switch m.Kind {
|
||||||
|
case ast.Union:
|
||||||
|
fqn := m.Descriptor.GetParent().GetFullyQualifiedName()
|
||||||
|
if _, ok := v.graphqlUnionFieldsByName[fqn]; !ok {
|
||||||
|
v.graphqlUnionFieldsByName[fqn] = map[string]*desc.FieldDescriptor{}
|
||||||
|
}
|
||||||
|
for _, tt := range m.GetTypes() {
|
||||||
|
for _, f := range tt.GetFields() {
|
||||||
|
v.graphqlUnionFieldsByName[fqn][f.Name] = f.FieldDescriptor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case ast.Object:
|
||||||
|
v.protoFieldsByName[m.Definition] = map[string]*ast.FieldDefinition{}
|
||||||
|
for _, f := range m.GetFields() {
|
||||||
|
if f.FieldDescriptor != nil {
|
||||||
|
v.protoFieldsByName[m.Definition][f.FieldDescriptor.GetName()] = f.FieldDefinition
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case ast.InputObject:
|
||||||
|
v.graphqlFieldsByName[m.Descriptor] = map[string]*desc.FieldDescriptor{}
|
||||||
|
for _, f := range m.GetFields() {
|
||||||
|
v.graphqlFieldsByName[m.Descriptor][f.Name] = f.FieldDescriptor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch msgDesc := m.Descriptor.(type) {
|
||||||
|
case *desc.MessageDescriptor:
|
||||||
|
v.objectsByFQN[m.GetFullyQualifiedName()] = m
|
||||||
|
v.objectsByName[m.Name] = msgDesc
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
type repository struct {
|
||||||
|
files SchemaDescriptorList
|
||||||
|
mu *sync.RWMutex
|
||||||
|
|
||||||
|
methodsByName map[ast.Operation]map[string]*desc.MethodDescriptor
|
||||||
|
objectsByName map[string]*desc.MessageDescriptor
|
||||||
|
objectsByFQN map[string]*ObjectDescriptor
|
||||||
|
graphqlFieldsByName map[desc.Descriptor]map[string]*desc.FieldDescriptor
|
||||||
|
protoFieldsByName map[*ast.Definition]map[string]*ast.FieldDefinition
|
||||||
|
graphqlUnionFieldsByName map[string]map[string]*desc.FieldDescriptor
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r repository) FindMethodByName(op ast.Operation, name string) *desc.MethodDescriptor {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
m, _ := r.methodsByName[op][name]
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r repository) FindObjectByName(name string) *desc.MessageDescriptor {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
o, _ := r.objectsByName[name]
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r repository) FindObjectByFullyQualifiedName(fqn string) (*desc.MessageDescriptor, *ast.Definition) {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
o, _ := r.objectsByFQN[fqn]
|
||||||
|
msg, _ := o.Descriptor.(*desc.MessageDescriptor)
|
||||||
|
return msg, o.Definition
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r repository) FindFieldByName(msg desc.Descriptor, name string) *desc.FieldDescriptor {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
f, _ := r.graphqlFieldsByName[msg][name]
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r repository) FindUnionFieldByMessageFQNAndName(fqn, name string) *desc.FieldDescriptor {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
f, _ := r.graphqlUnionFieldsByName[fqn][name]
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r repository) FindGraphqlFieldByProtoField(msg *ast.Definition, name string) *ast.FieldDefinition {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
f, _ := r.protoFieldsByName[msg][name]
|
||||||
|
return f
|
||||||
|
}
|
291
graphql/utils.go
Normal file
291
graphql/utils.go
Normal file
@ -0,0 +1,291 @@
|
|||||||
|
package generator
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/jhump/protoreflect/desc"
|
||||||
|
"google.golang.org/protobuf/proto"
|
||||||
|
descriptor "google.golang.org/protobuf/types/descriptorpb"
|
||||||
|
"google.golang.org/protobuf/types/pluginpb"
|
||||||
|
|
||||||
|
gqlpb "go.unistack.org/micro-proto/v3/graphql"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GraphqlMethodOptions(opts proto.Message) *gqlpb.Rpc {
|
||||||
|
if opts != nil {
|
||||||
|
v := proto.GetExtension(opts, gqlpb.E_Rpc)
|
||||||
|
if v != nil {
|
||||||
|
return v.(*gqlpb.Rpc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GraphqlServiceOptions(opts proto.Message) *gqlpb.Svc {
|
||||||
|
if opts != nil {
|
||||||
|
v := proto.GetExtension(opts, gqlpb.E_Svc)
|
||||||
|
if v != nil {
|
||||||
|
return v.(*gqlpb.Svc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GraphqlFieldOptions(opts proto.Message) *gqlpb.Field {
|
||||||
|
if opts != nil {
|
||||||
|
v := proto.GetExtension(opts, gqlpb.E_Field)
|
||||||
|
if v != nil && v.(*gqlpb.Field) != nil {
|
||||||
|
return v.(*gqlpb.Field)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GraphqlOneofOptions(opts proto.Message) *gqlpb.Oneof {
|
||||||
|
if opts != nil {
|
||||||
|
v := proto.GetExtension(opts, gqlpb.E_Oneof)
|
||||||
|
if v != nil && v.(*gqlpb.Oneof) != nil {
|
||||||
|
return v.(*gqlpb.Oneof)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GoCamelCase camel-cases a protobuf name for use as a Go identifier.
|
||||||
|
//
|
||||||
|
// If there is an interior underscore followed by a lower case letter,
|
||||||
|
// drop the underscore and convert the letter to upper case.
|
||||||
|
func GoCamelCase(s string) string {
|
||||||
|
// Invariant: if the next letter is lower case, it must be converted
|
||||||
|
// to upper case.
|
||||||
|
// That is, we process a word at a time, where words are marked by _ or
|
||||||
|
// upper case letter. Digits are treated as words.
|
||||||
|
var b []byte
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
c := s[i]
|
||||||
|
switch {
|
||||||
|
case c == '.' && i+1 < len(s) && isASCIILower(s[i+1]):
|
||||||
|
// Skip over '.' in ".{{lowercase}}".
|
||||||
|
case c == '.':
|
||||||
|
b = append(b, '_') // convert '.' to '_'
|
||||||
|
case c == '_' && (i == 0 || s[i-1] == '.'):
|
||||||
|
// Convert initial '_' to ensure we start with a capital letter.
|
||||||
|
// Do the same for '_' after '.' to match historic behavior.
|
||||||
|
b = append(b, 'X') // convert '_' to 'X'
|
||||||
|
case c == '_' && i+1 < len(s) && isASCIILower(s[i+1]):
|
||||||
|
// Skip over '_' in "_{{lowercase}}".
|
||||||
|
case isASCIIDigit(c):
|
||||||
|
b = append(b, c)
|
||||||
|
default:
|
||||||
|
// Assume we have a letter now - if not, it's a bogus identifier.
|
||||||
|
// The next word is a sequence of characters that must start upper case.
|
||||||
|
if isASCIILower(c) {
|
||||||
|
c -= 'a' - 'A' // convert lowercase to uppercase
|
||||||
|
}
|
||||||
|
b = append(b, c)
|
||||||
|
|
||||||
|
// Accept lower case sequence that follows.
|
||||||
|
for ; i+1 < len(s) && isASCIILower(s[i+1]); i++ {
|
||||||
|
b = append(b, s[i+1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetRequestType(rpcOpts *gqlpb.Rpc, svcOpts *gqlpb.Svc) gqlpb.Type {
|
||||||
|
if rpcOpts != nil && rpcOpts.Type != nil {
|
||||||
|
return *rpcOpts.Type
|
||||||
|
}
|
||||||
|
if svcOpts != nil && svcOpts.Type != nil {
|
||||||
|
return *svcOpts.Type
|
||||||
|
}
|
||||||
|
return gqlpb.Type_DEFAULT
|
||||||
|
}
|
||||||
|
|
||||||
|
func CreateDescriptorsFromProto(req *pluginpb.CodeGeneratorRequest) (descs []*desc.FileDescriptor, err error) {
|
||||||
|
dd, err := desc.CreateFileDescriptorsFromSet(&descriptor.FileDescriptorSet{
|
||||||
|
File: req.GetProtoFile(),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, d := range dd {
|
||||||
|
for _, filename := range req.FileToGenerate {
|
||||||
|
if filename == d.GetName() {
|
||||||
|
descs = append(descs, d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveProtoFilesRecursively(descs []*desc.FileDescriptor) (files FileDescriptors) {
|
||||||
|
for _, f := range descs {
|
||||||
|
files = append(files, ResolveProtoFilesRecursively(f.GetDependencies())...)
|
||||||
|
files = append(files, f)
|
||||||
|
}
|
||||||
|
|
||||||
|
return files
|
||||||
|
}
|
||||||
|
|
||||||
|
type FileDescriptors []*desc.FileDescriptor
|
||||||
|
|
||||||
|
func (ds FileDescriptors) AsFileDescriptorProto() (files []*descriptor.FileDescriptorProto) {
|
||||||
|
for _, d := range ds {
|
||||||
|
files = append(files, d.AsFileDescriptorProto())
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Split splits the camelcase word and returns a list of words. It also
|
||||||
|
// supports digits. Both lower camel case and upper camel case are supported.
|
||||||
|
// For more info please check: http://en.wikipedia.org/wiki/CamelCase
|
||||||
|
//
|
||||||
|
// Examples
|
||||||
|
//
|
||||||
|
// "" => [""]
|
||||||
|
// "lowercase" => ["lowercase"]
|
||||||
|
// "Class" => ["Class"]
|
||||||
|
// "MyClass" => ["My", "Class"]
|
||||||
|
// "MyC" => ["My", "C"]
|
||||||
|
// "HTML" => ["HTML"]
|
||||||
|
// "PDFLoader" => ["PDF", "Loader"]
|
||||||
|
// "AString" => ["A", "String"]
|
||||||
|
// "SimpleXMLParser" => ["Simple", "XML", "Parser"]
|
||||||
|
// "vimRPCPlugin" => ["vim", "RPC", "Plugin"]
|
||||||
|
// "GL11Version" => ["GL", "11", "Version"]
|
||||||
|
// "99Bottles" => ["99", "Bottles"]
|
||||||
|
// "May5" => ["May", "5"]
|
||||||
|
// "BFG9000" => ["BFG", "9000"]
|
||||||
|
// "BöseÜberraschung" => ["Böse", "Überraschung"]
|
||||||
|
// "Two spaces" => ["Two", " ", "spaces"]
|
||||||
|
// "BadUTF8\xe2\xe2\xa1" => ["BadUTF8\xe2\xe2\xa1"]
|
||||||
|
//
|
||||||
|
// Splitting rules
|
||||||
|
//
|
||||||
|
// 1. If string is not valid UTF-8, return it without splitting as
|
||||||
|
// single item array.
|
||||||
|
// 2. Assign all unicode characters into one of 4 sets: lower case
|
||||||
|
// letters, upper case letters, numbers, and all other characters.
|
||||||
|
// 3. Iterate through characters of string, introducing splits
|
||||||
|
// between adjacent characters that belong to different sets.
|
||||||
|
// 4. Iterate through array of split strings, and if a given string
|
||||||
|
// is upper case:
|
||||||
|
// if subsequent string is lower case:
|
||||||
|
// move last character of upper case string to beginning of
|
||||||
|
// lower case string
|
||||||
|
func SplitCamelCase(src string) (entries []string) {
|
||||||
|
// don't split invalid utf8
|
||||||
|
if !utf8.ValidString(src) {
|
||||||
|
return []string{src}
|
||||||
|
}
|
||||||
|
entries = []string{}
|
||||||
|
var runes [][]rune
|
||||||
|
lastClass := 0
|
||||||
|
class := 0
|
||||||
|
// split into fields based on class of unicode character
|
||||||
|
for _, r := range src {
|
||||||
|
switch true {
|
||||||
|
case unicode.IsLower(r):
|
||||||
|
class = 1
|
||||||
|
case unicode.IsUpper(r):
|
||||||
|
class = 2
|
||||||
|
case unicode.IsDigit(r):
|
||||||
|
class = 3
|
||||||
|
default:
|
||||||
|
class = 4
|
||||||
|
}
|
||||||
|
if class == lastClass {
|
||||||
|
runes[len(runes)-1] = append(runes[len(runes)-1], r)
|
||||||
|
} else {
|
||||||
|
runes = append(runes, []rune{r})
|
||||||
|
}
|
||||||
|
lastClass = class
|
||||||
|
}
|
||||||
|
// handle upper case -> lower case sequences, e.g.
|
||||||
|
// "PDFL", "oader" -> "PDF", "Loader"
|
||||||
|
for i := 0; i < len(runes)-1; i++ {
|
||||||
|
if unicode.IsUpper(runes[i][0]) && unicode.IsLower(runes[i+1][0]) {
|
||||||
|
runes[i+1] = append([]rune{runes[i][len(runes[i])-1]}, runes[i+1]...)
|
||||||
|
runes[i] = runes[i][:len(runes[i])-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// construct []string from results
|
||||||
|
for _, s := range runes {
|
||||||
|
if len(s) > 0 {
|
||||||
|
entries = append(entries, string(s))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// CamelCase returns the CamelCased name.
|
||||||
|
// If there is an interior underscore followed by a lower case letter,
|
||||||
|
// drop the underscore and convert the letter to upper case.
|
||||||
|
// There is a remote possibility of this rewrite causing a name collision,
|
||||||
|
// but it's so remote we're prepared to pretend it's nonexistent - since the
|
||||||
|
// C++ generator lowercases names, it's extremely unlikely to have two fields
|
||||||
|
// with different capitalizations.
|
||||||
|
// In short, _my_field_name_2 becomes XMyFieldName_2.
|
||||||
|
func CamelCase(s string) string {
|
||||||
|
if s == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
t := make([]byte, 0, 32)
|
||||||
|
i := 0
|
||||||
|
if s[0] == '_' {
|
||||||
|
// Need a capital letter; drop the '_'.
|
||||||
|
t = append(t, 'X')
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
// Invariant: if the next letter is lower case, it must be converted
|
||||||
|
// to upper case.
|
||||||
|
// That is, we process a word at a time, where words are marked by _ or
|
||||||
|
// upper case letter. Digits are treated as words.
|
||||||
|
for ; i < len(s); i++ {
|
||||||
|
c := s[i]
|
||||||
|
if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) {
|
||||||
|
continue // Skip the underscore in s.
|
||||||
|
}
|
||||||
|
if isASCIIDigit(c) {
|
||||||
|
t = append(t, c)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Assume we have a letter now - if not, it's a bogus identifier.
|
||||||
|
// The next word is a sequence of characters that must start upper case.
|
||||||
|
if isASCIILower(c) {
|
||||||
|
c ^= ' ' // Make it a capital letter.
|
||||||
|
}
|
||||||
|
t = append(t, c) // Guaranteed not lower case.
|
||||||
|
// Accept lower case sequence that follows.
|
||||||
|
for i+1 < len(s) && isASCIILower(s[i+1]) {
|
||||||
|
i++
|
||||||
|
t = append(t, s[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return string(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CamelCaseSlice is like CamelCase, but the argument is a slice of strings to
|
||||||
|
// be joined with "_".
|
||||||
|
func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) }
|
||||||
|
|
||||||
|
// Is c an ASCII lower-case letter?
|
||||||
|
func isASCIILower(c byte) bool {
|
||||||
|
return 'a' <= c && c <= 'z'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Is c an ASCII digit?
|
||||||
|
func isASCIIDigit(c byte) bool {
|
||||||
|
return '0' <= c && c <= '9'
|
||||||
|
}
|
||||||
|
|
||||||
|
func ToLowerFirst(s string) string {
|
||||||
|
if len(s) > 0 {
|
||||||
|
return string(unicode.ToLower(rune(s[0]))) + s[1:]
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
56
graphqls.go
Normal file
56
graphqls.go
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/vektah/gqlparser/v2/formatter"
|
||||||
|
generator "go.unistack.org/protoc-gen-go-micro/v3/graphql"
|
||||||
|
"google.golang.org/protobuf/compiler/protogen"
|
||||||
|
"google.golang.org/protobuf/proto"
|
||||||
|
"google.golang.org/protobuf/types/pluginpb"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (g *Generator) graphqlsGenerate(plugin *protogen.Plugin) error {
|
||||||
|
descs, err := generator.CreateDescriptorsFromProto(plugin.Request)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
gqlDesc, err := generator.NewSchemas(descs, false, false, plugin)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var outFiles []*pluginpb.CodeGeneratorResponse_File
|
||||||
|
|
||||||
|
for _, schema := range gqlDesc {
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
formatter.NewFormatter(buf).FormatSchema(schema.AsGraphql())
|
||||||
|
|
||||||
|
outFiles = append(outFiles, &pluginpb.CodeGeneratorResponse_File{
|
||||||
|
Name: proto.String(g.graphqlFile),
|
||||||
|
Content: proto.String(buf.String()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
res := &pluginpb.CodeGeneratorResponse{
|
||||||
|
File: outFiles,
|
||||||
|
SupportedFeatures: proto.Uint64(uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
res.Error = proto.String(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := proto.Marshal(res)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := os.Stdout.Write(out); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
12
http.go
12
http.go
@ -28,7 +28,6 @@ func (g *Generator) httpGenerate(component string, plugin *protogen.Plugin, genC
|
|||||||
gfile.P()
|
gfile.P()
|
||||||
|
|
||||||
gfile.Import(contextPackage)
|
gfile.Import(contextPackage)
|
||||||
gfile.Import(microApiPackage)
|
|
||||||
|
|
||||||
if genClient {
|
if genClient {
|
||||||
gfile.Import(microClientPackage)
|
gfile.Import(microClientPackage)
|
||||||
@ -39,14 +38,15 @@ func (g *Generator) httpGenerate(component string, plugin *protogen.Plugin, genC
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, service := range file.Services {
|
for _, service := range file.Services {
|
||||||
|
g.generateServiceEndpoints(gfile, service, component)
|
||||||
if genClient {
|
if genClient {
|
||||||
generateServiceClient(gfile, service)
|
g.generateServiceClient(gfile, file, service)
|
||||||
generateServiceClientMethods(gfile, service, true)
|
g.generateServiceClientMethods(gfile, service, component)
|
||||||
}
|
}
|
||||||
if genServer {
|
if genServer {
|
||||||
generateServiceServer(gfile, service)
|
g.generateServiceServer(gfile, file, service)
|
||||||
generateServiceServerMethods(gfile, service)
|
g.generateServiceServerMethods(gfile, service)
|
||||||
generateServiceRegister(gfile, service)
|
g.generateServiceRegister(gfile, file, service, component)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
61
main.go
61
main.go
@ -3,6 +3,7 @@ package main
|
|||||||
import (
|
import (
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"google.golang.org/protobuf/compiler/protogen"
|
"google.golang.org/protobuf/compiler/protogen"
|
||||||
@ -10,23 +11,27 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
flagDebug = flag.Bool("debug", false, "debug output")
|
flagSet = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
|
||||||
flagStandalone = flag.Bool("standalone", false, "generate file to standalone dir")
|
flagDebug = flagSet.Bool("debug", false, "debug output")
|
||||||
flagComponents = flag.String("components", "micro|rpc|http|client|server|openapiv3", "specify components to generate")
|
flagStandalone = flagSet.Bool("standalone", false, "generate file to standalone dir")
|
||||||
flagTagPath = flag.String("tag_path", "", "tag rewriting dir")
|
flagFieldaligment = flagSet.Bool("fieldaligment", false, "align struct fields in generated code")
|
||||||
flagOpenapiFile = flag.String("openapi_file", "apidocs.swagger.json", "openapi file name")
|
flagComponents = flagSet.String("components", "micro|rpc|http|client|server|openapiv3|graphql", "specify components to generate")
|
||||||
flagHelp = flag.Bool("help", false, "display help message")
|
flagTagPath = flagSet.String("tag_path", "", "tag rewriting dir")
|
||||||
|
flagOpenapiFile = flagSet.String("openapi_file", "apidocs.swagger.yaml", "openapi file name")
|
||||||
|
flagGraphqlFile = flagSet.String("graphql_file", "schema.graphqls", "graphql file name")
|
||||||
|
flagReflection = flagSet.Bool("reflection", false, "enable server reflection support")
|
||||||
|
flagHelp = flagSet.Bool("help", false, "display help message")
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
opts := &protogen.Options{
|
opts := &protogen.Options{
|
||||||
ParamFunc: flag.CommandLine.Set,
|
ParamFunc: flagSet.Set,
|
||||||
}
|
}
|
||||||
|
|
||||||
flag.Parse()
|
_ = flagSet.Parse(os.Args[1:])
|
||||||
|
|
||||||
if *flagHelp {
|
if *flagHelp {
|
||||||
flag.PrintDefaults()
|
flagSet.PrintDefaults()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -39,22 +44,31 @@ type Generator struct {
|
|||||||
components string
|
components string
|
||||||
standalone bool
|
standalone bool
|
||||||
debug bool
|
debug bool
|
||||||
|
fieldaligment bool
|
||||||
tagPath string
|
tagPath string
|
||||||
openapiFile string
|
openapiFile string
|
||||||
|
graphqlFile string
|
||||||
|
reflection bool
|
||||||
|
plugin *protogen.Plugin
|
||||||
}
|
}
|
||||||
|
|
||||||
func (g *Generator) Generate(plugin *protogen.Plugin) error {
|
func (g *Generator) Generate(plugin *protogen.Plugin) error {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
|
g.plugin = plugin
|
||||||
g.standalone = *flagStandalone
|
g.standalone = *flagStandalone
|
||||||
g.debug = *flagDebug
|
g.debug = *flagDebug
|
||||||
g.components = *flagComponents
|
g.components = *flagComponents
|
||||||
|
g.fieldaligment = *flagFieldaligment
|
||||||
g.tagPath = *flagTagPath
|
g.tagPath = *flagTagPath
|
||||||
g.openapiFile = *flagOpenapiFile
|
g.openapiFile = *flagOpenapiFile
|
||||||
|
g.graphqlFile = *flagGraphqlFile
|
||||||
|
g.reflection = *flagReflection
|
||||||
plugin.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)
|
plugin.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)
|
||||||
|
|
||||||
var genClient bool
|
genClient := true
|
||||||
var genServer bool
|
genServer := true
|
||||||
|
var genNone bool
|
||||||
|
|
||||||
if strings.Contains(g.components, "server") {
|
if strings.Contains(g.components, "server") {
|
||||||
genServer = true
|
genServer = true
|
||||||
@ -62,8 +76,11 @@ func (g *Generator) Generate(plugin *protogen.Plugin) error {
|
|||||||
if strings.Contains(g.components, "client") {
|
if strings.Contains(g.components, "client") {
|
||||||
genClient = true
|
genClient = true
|
||||||
}
|
}
|
||||||
|
if strings.Contains(g.components, "none") {
|
||||||
|
genNone = true
|
||||||
|
}
|
||||||
if strings.Contains(g.components, "rpc") || strings.Contains(g.components, "http") {
|
if strings.Contains(g.components, "rpc") || strings.Contains(g.components, "http") {
|
||||||
if !genServer && !genClient {
|
if !genServer && !genClient && !genNone {
|
||||||
genServer = true
|
genServer = true
|
||||||
genClient = true
|
genClient = true
|
||||||
}
|
}
|
||||||
@ -76,16 +93,25 @@ func (g *Generator) Generate(plugin *protogen.Plugin) error {
|
|||||||
continue
|
continue
|
||||||
case "micro":
|
case "micro":
|
||||||
err = g.microGenerate(component, plugin, genClient, genServer)
|
err = g.microGenerate(component, plugin, genClient, genServer)
|
||||||
|
if err == nil {
|
||||||
|
err = g.writeErrors(plugin)
|
||||||
|
}
|
||||||
case "http":
|
case "http":
|
||||||
err = g.httpGenerate(component, plugin, genClient, genServer)
|
err = g.httpGenerate(component, plugin, genClient, genServer)
|
||||||
case "grpc", "rpc":
|
case "grpc", "drpc", "rpc":
|
||||||
err = g.rpcGenerate("rpc", plugin, genClient, genServer)
|
err = g.rpcGenerate(component, plugin, genClient, genServer)
|
||||||
case "gorilla":
|
case "gorilla":
|
||||||
err = g.gorillaGenerate(component, plugin)
|
err = g.gorillaGenerate(component, plugin)
|
||||||
case "chi":
|
case "chi":
|
||||||
err = g.chiGenerate(component, plugin)
|
err = g.chiGenerate(component, plugin)
|
||||||
case "openapiv3":
|
case "openapiv3":
|
||||||
err = g.openapiv3Generate(component, plugin)
|
err = g.openapiv3Generate(plugin)
|
||||||
|
case "graphqls":
|
||||||
|
err = g.graphqlsGenerate(plugin)
|
||||||
|
case "graphql":
|
||||||
|
err = g.graphqlGenerate(plugin)
|
||||||
|
case "none":
|
||||||
|
break
|
||||||
default:
|
default:
|
||||||
err = fmt.Errorf("unknown component: %s", component)
|
err = fmt.Errorf("unknown component: %s", component)
|
||||||
}
|
}
|
||||||
@ -102,5 +128,10 @@ func (g *Generator) Generate(plugin *protogen.Plugin) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err = g.fieldAlign(plugin); err != nil {
|
||||||
|
plugin.Error(err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
32
micro.go
32
micro.go
@ -1,6 +1,8 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"google.golang.org/protobuf/compiler/protogen"
|
"google.golang.org/protobuf/compiler/protogen"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -22,27 +24,29 @@ func (g *Generator) microGenerate(component string, plugin *protogen.Plugin, gen
|
|||||||
gfile := plugin.NewGeneratedFile(gname, path)
|
gfile := plugin.NewGeneratedFile(gname, path)
|
||||||
|
|
||||||
gfile.P("// Code generated by protoc-gen-go-micro. DO NOT EDIT.")
|
gfile.P("// Code generated by protoc-gen-go-micro. DO NOT EDIT.")
|
||||||
gfile.P("// protoc-gen-go-micro version: " + versionComment)
|
gfile.P("// versions:")
|
||||||
gfile.P("// source: ", file.Proto.GetName())
|
gfile.P("// - protoc-gen-go-micro " + versionComment)
|
||||||
|
gfile.P("// - protoc ", protocVersion(plugin))
|
||||||
|
gfile.P("// source: ", file.Desc.Path())
|
||||||
gfile.P()
|
gfile.P()
|
||||||
gfile.P("package ", file.GoPackageName)
|
gfile.P("package ", file.GoPackageName)
|
||||||
gfile.P()
|
gfile.P()
|
||||||
|
|
||||||
gfile.Import(contextPackage)
|
gfile.Import(contextPackage)
|
||||||
gfile.Import(microApiPackage)
|
|
||||||
if genClient {
|
if genClient {
|
||||||
gfile.Import(microClientPackage)
|
gfile.Import(microClientPackage)
|
||||||
}
|
}
|
||||||
// generate services
|
// generate services
|
||||||
for _, service := range file.Services {
|
for _, service := range file.Services {
|
||||||
generateServiceEndpoints(gfile, service)
|
g.generateServiceName(gfile, service)
|
||||||
if genClient {
|
if genClient {
|
||||||
generateServiceClientInterface(gfile, service)
|
g.generateServiceClientInterface(gfile, service)
|
||||||
generateServiceClientStreamInterface(gfile, service)
|
g.generateServiceClientStreamInterface(gfile, service)
|
||||||
}
|
}
|
||||||
if genServer {
|
if genServer {
|
||||||
generateServiceServerInterface(gfile, service)
|
g.generateServiceServerInterface(gfile, service)
|
||||||
generateServiceServerStreamInterface(gfile, service)
|
g.generateServiceServerStreamInterface(gfile, service)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -50,3 +54,15 @@ func (g *Generator) microGenerate(component string, plugin *protogen.Plugin, gen
|
|||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func protocVersion(plugin *protogen.Plugin) string {
|
||||||
|
v := plugin.Request.GetCompilerVersion()
|
||||||
|
if v == nil {
|
||||||
|
return "(unknown)"
|
||||||
|
}
|
||||||
|
var suffix string
|
||||||
|
if s := v.GetSuffix(); s != "" {
|
||||||
|
suffix = "-" + s
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("v%d.%d.%d%s", v.GetMajor(), v.GetMinor(), v.GetPatch(), suffix)
|
||||||
|
}
|
||||||
|
1074
openapiv3.go
1074
openapiv3.go
File diff suppressed because it is too large
Load Diff
39
openapiv3_util.go
Normal file
39
openapiv3_util.go
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import v3 "go.unistack.org/micro-proto/v3/openapiv3"
|
||||||
|
|
||||||
|
func getMediaType(eopt interface{}) string {
|
||||||
|
ctype := "application/json"
|
||||||
|
|
||||||
|
if eopt == nil {
|
||||||
|
return ctype
|
||||||
|
}
|
||||||
|
|
||||||
|
if eopt == v3.E_Openapiv3Operation.InterfaceOf(v3.E_Openapiv3Operation.Zero()) {
|
||||||
|
return ctype
|
||||||
|
}
|
||||||
|
|
||||||
|
opt, ok := eopt.(*v3.Operation)
|
||||||
|
if !ok || opt.RequestBody == nil {
|
||||||
|
return ctype
|
||||||
|
}
|
||||||
|
|
||||||
|
if opt.GetRequestBody() == nil {
|
||||||
|
return ctype
|
||||||
|
}
|
||||||
|
|
||||||
|
if opt.GetRequestBody().GetRequestBody() == nil {
|
||||||
|
return ctype
|
||||||
|
}
|
||||||
|
|
||||||
|
c := opt.GetRequestBody().GetRequestBody().GetContent()
|
||||||
|
if c == nil {
|
||||||
|
return ctype
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, prop := range c.GetAdditionalProperties() {
|
||||||
|
ctype = prop.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
return ctype
|
||||||
|
}
|
15
rpc.go
15
rpc.go
@ -28,7 +28,7 @@ func (g *Generator) rpcGenerate(component string, plugin *protogen.Plugin, genCl
|
|||||||
gfile.P()
|
gfile.P()
|
||||||
|
|
||||||
gfile.Import(contextPackage)
|
gfile.Import(contextPackage)
|
||||||
gfile.Import(microApiPackage)
|
|
||||||
if genClient {
|
if genClient {
|
||||||
gfile.Import(microClientPackage)
|
gfile.Import(microClientPackage)
|
||||||
}
|
}
|
||||||
@ -37,13 +37,16 @@ func (g *Generator) rpcGenerate(component string, plugin *protogen.Plugin, genCl
|
|||||||
}
|
}
|
||||||
for _, service := range file.Services {
|
for _, service := range file.Services {
|
||||||
if genClient {
|
if genClient {
|
||||||
generateServiceClient(gfile, service)
|
g.generateServiceClient(gfile, file, service)
|
||||||
generateServiceClientMethods(gfile, service, false)
|
g.generateServiceClientMethods(gfile, service, component)
|
||||||
}
|
}
|
||||||
if genServer {
|
if genServer {
|
||||||
generateServiceServer(gfile, service)
|
g.generateServiceServer(gfile, file, service)
|
||||||
generateServiceServerMethods(gfile, service)
|
g.generateServiceServerMethods(gfile, service)
|
||||||
generateServiceRegister(gfile, service)
|
g.generateServiceRegister(gfile, file, service, component)
|
||||||
|
}
|
||||||
|
if component == "grpc" && g.reflection {
|
||||||
|
g.generateServiceDesc(gfile, file, service)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
7
tools.go
Normal file
7
tools.go
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
//go:build ignore
|
||||||
|
|
||||||
|
package tools
|
||||||
|
|
||||||
|
import (
|
||||||
|
_ "go.unistack.org/micro-proto/v3/graphql"
|
||||||
|
)
|
517
util.go
517
util.go
@ -2,8 +2,11 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
api_options "go.unistack.org/micro-proto/v3/api"
|
api_options "go.unistack.org/micro-proto/v3/api"
|
||||||
v2 "go.unistack.org/micro-proto/v3/openapiv2"
|
v2 "go.unistack.org/micro-proto/v3/openapiv2"
|
||||||
@ -28,7 +31,7 @@ func unexport(s string) string {
|
|||||||
return strings.ToLower(s[:1]) + s[1:]
|
return strings.ToLower(s[:1]) + s[1:]
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateServiceClient(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
func (g *Generator) generateServiceClient(gfile *protogen.GeneratedFile, file *protogen.File, service *protogen.Service) {
|
||||||
serviceName := service.GoName
|
serviceName := service.GoName
|
||||||
// if rule, ok := getMicroApiService(service); ok {
|
// if rule, ok := getMicroApiService(service); ok {
|
||||||
// gfile.P("// client wrappers ", strings.Join(rule.ClientWrappers, ", "))
|
// gfile.P("// client wrappers ", strings.Join(rule.ClientWrappers, ", "))
|
||||||
@ -38,34 +41,96 @@ func generateServiceClient(gfile *protogen.GeneratedFile, service *protogen.Serv
|
|||||||
gfile.P("name string")
|
gfile.P("name string")
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
|
|
||||||
|
if g.standalone {
|
||||||
|
gfile.P("func New", serviceName, "Client(name string, c ", microClientPackage.Ident("Client"), ") ", file.GoImportPath.Ident(serviceName), "Client {")
|
||||||
|
} else {
|
||||||
gfile.P("func New", serviceName, "Client(name string, c ", microClientPackage.Ident("Client"), ") ", serviceName, "Client {")
|
gfile.P("func New", serviceName, "Client(name string, c ", microClientPackage.Ident("Client"), ") ", serviceName, "Client {")
|
||||||
|
}
|
||||||
gfile.P("return &", unexport(serviceName), "Client{c: c, name: name}")
|
gfile.P("return &", unexport(serviceName), "Client{c: c, name: name}")
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
gfile.P()
|
gfile.P()
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateServiceClientMethods(gfile *protogen.GeneratedFile, service *protogen.Service, http bool) {
|
func (g *Generator) generateServiceClientMethods(gfile *protogen.GeneratedFile, service *protogen.Service, component string) {
|
||||||
serviceName := service.GoName
|
serviceName := service.GoName
|
||||||
for _, method := range service.Methods {
|
for _, method := range service.Methods {
|
||||||
methodName := fmt.Sprintf("%s.%s", serviceName, method.GoName)
|
methodName := fmt.Sprintf("%s.%s", serviceName, method.GoName)
|
||||||
generateClientFuncSignature(gfile, serviceName, method)
|
if component == "drpc" {
|
||||||
|
methodName = fmt.Sprintf("%s.%s", method.Parent.Desc.FullName(), method.Desc.Name())
|
||||||
|
}
|
||||||
|
g.generateClientFuncSignature(gfile, serviceName, method)
|
||||||
|
|
||||||
if http && method.Desc.Options() != nil {
|
if component == "http" && method.Desc.Options() != nil {
|
||||||
if proto.HasExtension(method.Desc.Options(), v2.E_Openapiv2Operation) {
|
if proto.HasExtension(method.Desc.Options(), v2.E_Openapiv2Operation) {
|
||||||
opts := proto.GetExtension(method.Desc.Options(), v2.E_Openapiv2Operation)
|
opts := proto.GetExtension(method.Desc.Options(), v2.E_Openapiv2Operation)
|
||||||
if opts != nil {
|
if opts != nil {
|
||||||
r := opts.(*v2.Operation)
|
r := opts.(*v2.Operation)
|
||||||
|
if r.Responses == nil {
|
||||||
|
goto labelMethod
|
||||||
|
}
|
||||||
gfile.P("errmap := make(map[string]interface{}, ", len(r.Responses.ResponseCode), ")")
|
gfile.P("errmap := make(map[string]interface{}, ", len(r.Responses.ResponseCode), ")")
|
||||||
for _, rsp := range r.Responses.ResponseCode {
|
for _, rsp := range r.Responses.ResponseCode {
|
||||||
if schema := rsp.Value.GetJsonReference(); schema != nil {
|
if schema := rsp.Value.GetJsonReference(); schema != nil {
|
||||||
ref := schema.XRef
|
xref := schema.XRef
|
||||||
if strings.HasPrefix(ref, "."+string(service.Desc.ParentFile().Package())+".") {
|
if strings.HasPrefix(xref, "."+string(service.Desc.ParentFile().Package())+".") {
|
||||||
ref = strings.TrimPrefix(ref, "."+string(service.Desc.ParentFile().Package())+".")
|
xref = strings.TrimPrefix(xref, "."+string(service.Desc.ParentFile().Package())+".")
|
||||||
}
|
}
|
||||||
if ref == "micro.codec.Frame" || ref == ".micro.codec.Frame" {
|
if xref[0] == '.' {
|
||||||
|
xref = xref[1:]
|
||||||
|
}
|
||||||
|
switch xref {
|
||||||
|
case "micro.codec.Frame":
|
||||||
gfile.P(`errmap["`, rsp.Name, `"] = &`, microCodecPackage.Ident("Frame"), "{}")
|
gfile.P(`errmap["`, rsp.Name, `"] = &`, microCodecPackage.Ident("Frame"), "{}")
|
||||||
} else {
|
case "micro.errors.Error":
|
||||||
gfile.P(`errmap["`, rsp.Name, `"] = &`, ref, "{}")
|
gfile.P(`errmap["`, rsp.Name, `"] = &`, microErrorsPackage.Ident("Error"), "{}")
|
||||||
|
default:
|
||||||
|
ident, err := g.getGoIdentByXref(strings.TrimPrefix(schema.XRef, "."))
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("cant find message by ref %s\n", schema.XRef)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
gfile.P(`errmap["`, rsp.Name, `"] = &`, gfile.QualifiedGoIdent(ident), "{}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gfile.P("opts = append(opts,")
|
||||||
|
gfile.P(microClientHttpPackage.Ident("ErrorMap"), "(errmap),")
|
||||||
|
gfile.P(")")
|
||||||
|
}
|
||||||
|
if proto.HasExtension(method.Desc.Options(), v3.E_Openapiv3Operation) {
|
||||||
|
opts := proto.GetExtension(method.Desc.Options(), v3.E_Openapiv3Operation)
|
||||||
|
if opts != nil {
|
||||||
|
r := opts.(*v3.Operation)
|
||||||
|
if r.Responses == nil {
|
||||||
|
goto labelMethod
|
||||||
|
}
|
||||||
|
resps := r.Responses.ResponseOrReference
|
||||||
|
if r.Responses.GetDefault() != nil {
|
||||||
|
resps = append(resps, &v3.NamedResponseOrReference{Name: "default", Value: r.Responses.GetDefault()})
|
||||||
|
}
|
||||||
|
gfile.P("errmap := make(map[string]interface{}, ", len(resps), ")")
|
||||||
|
for _, rsp := range resps {
|
||||||
|
if schema := rsp.Value.GetReference(); schema != nil {
|
||||||
|
xref := schema.XRef
|
||||||
|
if strings.HasPrefix(xref, "."+string(service.Desc.ParentFile().Package())+".") {
|
||||||
|
xref = strings.TrimPrefix(xref, "."+string(service.Desc.ParentFile().Package())+".")
|
||||||
|
}
|
||||||
|
if xref[0] == '.' {
|
||||||
|
xref = xref[1:]
|
||||||
|
}
|
||||||
|
switch xref {
|
||||||
|
case "micro.codec.Frame":
|
||||||
|
gfile.P(`errmap["`, rsp.Name, `"] = &`, microCodecPackage.Ident("Frame"), "{}")
|
||||||
|
case "micro.errors.Error":
|
||||||
|
gfile.P(`errmap["`, rsp.Name, `"] = &`, microErrorsPackage.Ident("Error"), "{}")
|
||||||
|
default:
|
||||||
|
ident, err := g.getGoIdentByXref(strings.TrimPrefix(schema.XRef, "."))
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("cant find message by ref %s\n", schema.XRef)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
gfile.P(`errmap["`, rsp.Name, `"] = &`, gfile.QualifiedGoIdent(ident), "{}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -75,6 +140,7 @@ func generateServiceClientMethods(gfile *protogen.GeneratedFile, service *protog
|
|||||||
gfile.P(")")
|
gfile.P(")")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
labelMethod:
|
||||||
if proto.HasExtension(method.Desc.Options(), api_options.E_Http) {
|
if proto.HasExtension(method.Desc.Options(), api_options.E_Http) {
|
||||||
gfile.P("opts = append(opts,")
|
gfile.P("opts = append(opts,")
|
||||||
endpoints, _ := generateEndpoints(method)
|
endpoints, _ := generateEndpoints(method)
|
||||||
@ -93,10 +159,36 @@ func generateServiceClientMethods(gfile *protogen.GeneratedFile, service *protog
|
|||||||
|
|
||||||
parameters := make(map[string]map[string]string)
|
parameters := make(map[string]map[string]string)
|
||||||
// Build a list of header parameters.
|
// Build a list of header parameters.
|
||||||
eopt := proto.GetExtension(method.Desc.Options(), v3.E_Openapiv3Operation)
|
e2opt := proto.GetExtension(method.Desc.Options(), v2.E_Openapiv2Operation)
|
||||||
if eopt != nil && eopt != v3.E_Openapiv3Operation.InterfaceOf(v3.E_Openapiv3Operation.Zero()) {
|
if e2opt != nil && e2opt != v2.E_Openapiv2Operation.InterfaceOf(v2.E_Openapiv2Operation.Zero()) {
|
||||||
opt := eopt.(*v3.Operation)
|
opt := e2opt.(*v2.Operation)
|
||||||
for _, paramOrRef := range opt.Parameters {
|
for _, paramOrRef := range opt.Parameters {
|
||||||
|
parameter := paramOrRef.GetParameter()
|
||||||
|
// NonBodyParameter()
|
||||||
|
if parameter == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
nonBodyParameter := parameter.GetNonBodyParameter()
|
||||||
|
if nonBodyParameter == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
headerParameter := nonBodyParameter.GetHeaderParameterSubSchema()
|
||||||
|
if headerParameter.In != "header" && headerParameter.In != "cookie" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
in, ok := parameters[headerParameter.In]
|
||||||
|
if !ok {
|
||||||
|
in = make(map[string]string)
|
||||||
|
parameters[headerParameter.In] = in
|
||||||
|
}
|
||||||
|
in[headerParameter.Name] = fmt.Sprintf("%v", headerParameter.Required)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e3opt := proto.GetExtension(method.Desc.Options(), v3.E_Openapiv3Operation)
|
||||||
|
if e3opt != nil && e3opt != v3.E_Openapiv3Operation.InterfaceOf(v3.E_Openapiv3Operation.Zero()) {
|
||||||
|
opt := e3opt.(*v3.Operation)
|
||||||
|
for _, paramOrRef := range opt.Parameters {
|
||||||
|
|
||||||
parameter := paramOrRef.GetParameter()
|
parameter := paramOrRef.GetParameter()
|
||||||
if parameter == nil {
|
if parameter == nil {
|
||||||
continue
|
continue
|
||||||
@ -127,8 +219,14 @@ func generateServiceClientMethods(gfile *protogen.GeneratedFile, service *protog
|
|||||||
}
|
}
|
||||||
|
|
||||||
if rule, ok := getMicroApiMethod(method); ok {
|
if rule, ok := getMicroApiMethod(method); ok {
|
||||||
if rule.Timeout > 0 {
|
if rule.Timeout != "" {
|
||||||
gfile.P("opts = append(opts, ", microClientPackage.Ident("WithRequestTimeout"), "(", timePackage.Ident("Second"), "*", rule.Timeout, "))")
|
td, err := time.ParseDuration(rule.Timeout)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("parse duration error %s\n", err.Error())
|
||||||
|
} else {
|
||||||
|
gfile.P("td := ", timePackage.Ident("Duration"), "(", td.Nanoseconds(), ")")
|
||||||
|
gfile.P("opts = append(opts, ", microClientPackage.Ident("WithRequestTimeout"), "(td))")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -165,7 +263,7 @@ func generateServiceClientMethods(gfile *protogen.GeneratedFile, service *protog
|
|||||||
}
|
}
|
||||||
|
|
||||||
if method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
|
if method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
|
||||||
gfile.P("func (s *", unexport(serviceName), "Client", method.GoName, ") RecvAndClose() (*", gfile.QualifiedGoIdent(method.Output.GoIdent), ", error) {")
|
gfile.P("func (s *", unexport(serviceName), "Client", method.GoName, ") CloseAndRecv() (*", gfile.QualifiedGoIdent(method.Output.GoIdent), ", error) {")
|
||||||
gfile.P("msg := &", gfile.QualifiedGoIdent(method.Output.GoIdent), "{}")
|
gfile.P("msg := &", gfile.QualifiedGoIdent(method.Output.GoIdent), "{}")
|
||||||
gfile.P("err := s.RecvMsg(msg)")
|
gfile.P("err := s.RecvMsg(msg)")
|
||||||
gfile.P("if err == nil {")
|
gfile.P("if err == nil {")
|
||||||
@ -183,6 +281,10 @@ func generateServiceClientMethods(gfile *protogen.GeneratedFile, service *protog
|
|||||||
gfile.P("return s.stream.Close()")
|
gfile.P("return s.stream.Close()")
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
gfile.P()
|
gfile.P()
|
||||||
|
gfile.P("func (s *", unexport(serviceName), "Client", method.GoName, ") CloseSend() error {")
|
||||||
|
gfile.P("return s.stream.CloseSend()")
|
||||||
|
gfile.P("}")
|
||||||
|
gfile.P()
|
||||||
gfile.P("func (s *", unexport(serviceName), "Client", method.GoName, ") Context() ", contextPackage.Ident("Context"), " {")
|
gfile.P("func (s *", unexport(serviceName), "Client", method.GoName, ") Context() ", contextPackage.Ident("Context"), " {")
|
||||||
gfile.P("return s.stream.Context()")
|
gfile.P("return s.stream.Context()")
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
@ -197,6 +299,11 @@ func generateServiceClientMethods(gfile *protogen.GeneratedFile, service *protog
|
|||||||
gfile.P()
|
gfile.P()
|
||||||
|
|
||||||
if method.Desc.IsStreamingClient() {
|
if method.Desc.IsStreamingClient() {
|
||||||
|
gfile.P("func (s *", unexport(serviceName), "Client", method.GoName, ") Header() ", microMetadataPackage.Ident("Metadata"), "{")
|
||||||
|
gfile.P("return s.stream.Response().Header()")
|
||||||
|
gfile.P("}")
|
||||||
|
gfile.P()
|
||||||
|
|
||||||
gfile.P("func (s *", unexport(serviceName), "Client", method.GoName, ") Send(msg *", gfile.QualifiedGoIdent(method.Input.GoIdent), ") error {")
|
gfile.P("func (s *", unexport(serviceName), "Client", method.GoName, ") Send(msg *", gfile.QualifiedGoIdent(method.Input.GoIdent), ") error {")
|
||||||
gfile.P("return s.stream.Send(msg)")
|
gfile.P("return s.stream.Send(msg)")
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
@ -216,25 +323,35 @@ func generateServiceClientMethods(gfile *protogen.GeneratedFile, service *protog
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateServiceServer(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
func (g *Generator) generateServiceServer(gfile *protogen.GeneratedFile, file *protogen.File, service *protogen.Service) {
|
||||||
serviceName := service.GoName
|
serviceName := service.GoName
|
||||||
gfile.P("type ", unexport(serviceName), "Server struct {")
|
gfile.P("type ", unexport(serviceName), "Server struct {")
|
||||||
|
if g.standalone {
|
||||||
|
gfile.P(file.GoImportPath.Ident(serviceName), "Server")
|
||||||
|
} else {
|
||||||
gfile.P(serviceName, "Server")
|
gfile.P(serviceName, "Server")
|
||||||
|
}
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
gfile.P()
|
gfile.P()
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateServiceServerMethods(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
func (g *Generator) generateServiceServerMethods(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
||||||
serviceName := service.GoName
|
serviceName := service.GoName
|
||||||
for _, method := range service.Methods {
|
for _, method := range service.Methods {
|
||||||
generateServerFuncSignature(gfile, serviceName, method, true)
|
generateServerFuncSignature(gfile, serviceName, method, true)
|
||||||
if rule, ok := getMicroApiMethod(method); ok {
|
if rule, ok := getMicroApiMethod(method); ok {
|
||||||
if rule.Timeout > 0 {
|
if rule.Timeout != "" {
|
||||||
|
td, err := time.ParseDuration(rule.Timeout)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("parse duration error %s\n", err.Error())
|
||||||
|
} else {
|
||||||
gfile.P("var cancel ", contextPackage.Ident("CancelFunc"))
|
gfile.P("var cancel ", contextPackage.Ident("CancelFunc"))
|
||||||
gfile.P("ctx, cancel = ", contextPackage.Ident("WithTimeout"), "(ctx, ", timePackage.Ident("Second"), "*", rule.Timeout, ")")
|
gfile.P("td := ", timePackage.Ident("Duration"), "(", td.Nanoseconds(), ")")
|
||||||
|
gfile.P("ctx, cancel = ", contextPackage.Ident("WithTimeout"), "(ctx, ", "td", ")")
|
||||||
gfile.P("defer cancel()")
|
gfile.P("defer cancel()")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
|
if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
|
||||||
if !method.Desc.IsStreamingClient() {
|
if !method.Desc.IsStreamingClient() {
|
||||||
gfile.P("msg := &", gfile.QualifiedGoIdent(method.Input.GoIdent), "{}")
|
gfile.P("msg := &", gfile.QualifiedGoIdent(method.Input.GoIdent), "{}")
|
||||||
@ -248,9 +365,34 @@ func generateServiceServerMethods(gfile *protogen.GeneratedFile, service *protog
|
|||||||
} else {
|
} else {
|
||||||
parameters := make(map[string]map[string]string)
|
parameters := make(map[string]map[string]string)
|
||||||
// Build a list of header parameters.
|
// Build a list of header parameters.
|
||||||
eopt := proto.GetExtension(method.Desc.Options(), v3.E_Openapiv3Operation)
|
e2opt := proto.GetExtension(method.Desc.Options(), v2.E_Openapiv2Operation)
|
||||||
if eopt != nil && eopt != v3.E_Openapiv3Operation.InterfaceOf(v3.E_Openapiv3Operation.Zero()) {
|
if e2opt != nil && e2opt != v2.E_Openapiv2Operation.InterfaceOf(v2.E_Openapiv2Operation.Zero()) {
|
||||||
opt := eopt.(*v3.Operation)
|
opt := e2opt.(*v2.Operation)
|
||||||
|
for _, paramOrRef := range opt.Parameters {
|
||||||
|
parameter := paramOrRef.GetParameter()
|
||||||
|
// NonBodyParameter()
|
||||||
|
if parameter == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
nonBodyParameter := parameter.GetNonBodyParameter()
|
||||||
|
if nonBodyParameter == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
headerParameter := nonBodyParameter.GetHeaderParameterSubSchema()
|
||||||
|
if headerParameter.In != "header" && headerParameter.In != "cookie" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
in, ok := parameters[headerParameter.In]
|
||||||
|
if !ok {
|
||||||
|
in = make(map[string]string)
|
||||||
|
parameters[headerParameter.In] = in
|
||||||
|
}
|
||||||
|
in[headerParameter.Name] = fmt.Sprintf("%v", headerParameter.Required)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e3opt := proto.GetExtension(method.Desc.Options(), v3.E_Openapiv3Operation)
|
||||||
|
if e3opt != nil && e3opt != v3.E_Openapiv3Operation.InterfaceOf(v3.E_Openapiv3Operation.Zero()) {
|
||||||
|
opt := e3opt.(*v3.Operation)
|
||||||
for _, paramOrRef := range opt.Parameters {
|
for _, paramOrRef := range opt.Parameters {
|
||||||
parameter := paramOrRef.GetParameter()
|
parameter := paramOrRef.GetParameter()
|
||||||
if parameter == nil {
|
if parameter == nil {
|
||||||
@ -269,7 +411,7 @@ func generateServiceServerMethods(gfile *protogen.GeneratedFile, service *protog
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(parameters) > 0 {
|
if len(parameters) > 0 {
|
||||||
gfile.P(microServerHttpPackage.Ident("FillRequest"), `(req, `)
|
gfile.P(microServerHttpPackage.Ident("FillRequest"), `(ctx, req, `)
|
||||||
for pk, pv := range parameters {
|
for pk, pv := range parameters {
|
||||||
params := make([]string, 0, len(pv)/2)
|
params := make([]string, 0, len(pv)/2)
|
||||||
for k, v := range pv {
|
for k, v := range pv {
|
||||||
@ -343,9 +485,13 @@ func generateServiceServerMethods(gfile *protogen.GeneratedFile, service *protog
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateServiceRegister(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
func (g *Generator) generateServiceRegister(gfile *protogen.GeneratedFile, file *protogen.File, service *protogen.Service, component string) {
|
||||||
serviceName := service.GoName
|
serviceName := service.GoName
|
||||||
|
if g.standalone {
|
||||||
|
gfile.P("func Register", serviceName, "Server(s ", microServerPackage.Ident("Server"), ", sh ", file.GoImportPath.Ident(serviceName), "Server, opts ...", microServerPackage.Ident("HandlerOption"), ") error {")
|
||||||
|
} else {
|
||||||
gfile.P("func Register", serviceName, "Server(s ", microServerPackage.Ident("Server"), ", sh ", serviceName, "Server, opts ...", microServerPackage.Ident("HandlerOption"), ") error {")
|
gfile.P("func Register", serviceName, "Server(s ", microServerPackage.Ident("Server"), ", sh ", serviceName, "Server, opts ...", microServerPackage.Ident("HandlerOption"), ") error {")
|
||||||
|
}
|
||||||
gfile.P("type ", unexport(serviceName), " interface {")
|
gfile.P("type ", unexport(serviceName), " interface {")
|
||||||
for _, method := range service.Methods {
|
for _, method := range service.Methods {
|
||||||
generateServerSignature(gfile, serviceName, method, true)
|
generateServerSignature(gfile, serviceName, method, true)
|
||||||
@ -356,9 +502,13 @@ func generateServiceRegister(gfile *protogen.GeneratedFile, service *protogen.Se
|
|||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
gfile.P("h := &", unexport(serviceName), "Server{sh}")
|
gfile.P("h := &", unexport(serviceName), "Server{sh}")
|
||||||
gfile.P("var nopts []", microServerPackage.Ident("HandlerOption"))
|
gfile.P("var nopts []", microServerPackage.Ident("HandlerOption"))
|
||||||
gfile.P("for _, endpoint := range ", serviceName, "Endpoints {")
|
if component == "http" {
|
||||||
gfile.P("nopts = append(nopts, ", microApiPackage.Ident("WithEndpoint"), "(&endpoint))")
|
// if g.standalone {
|
||||||
gfile.P("}")
|
// gfile.P("nopts = append(nopts, ", microServerHttpPackage.Ident("HandlerEndpoints"), "(", file.GoImportPath.Ident(serviceName), "ServerEndpoints))")
|
||||||
|
// } else {
|
||||||
|
gfile.P("nopts = append(nopts, ", microServerHttpPackage.Ident("HandlerEndpoints"), "(", serviceName, "ServerEndpoints))")
|
||||||
|
// }
|
||||||
|
}
|
||||||
gfile.P("return s.Handle(s.NewHandler(&", serviceName, "{h}, append(nopts, opts...)...))")
|
gfile.P("return s.Handle(s.NewHandler(&", serviceName, "{h}, append(nopts, opts...)...))")
|
||||||
gfile.P("}")
|
gfile.P("}")
|
||||||
}
|
}
|
||||||
@ -407,7 +557,7 @@ func generateServerSignature(gfile *protogen.GeneratedFile, serviceName string,
|
|||||||
gfile.P(args...)
|
gfile.P(args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateClientFuncSignature(gfile *protogen.GeneratedFile, serviceName string, method *protogen.Method) {
|
func (g *Generator) generateClientFuncSignature(gfile *protogen.GeneratedFile, serviceName string, method *protogen.Method) {
|
||||||
args := append([]interface{}{},
|
args := append([]interface{}{},
|
||||||
"func (c *",
|
"func (c *",
|
||||||
unexport(serviceName),
|
unexport(serviceName),
|
||||||
@ -422,7 +572,7 @@ func generateClientFuncSignature(gfile *protogen.GeneratedFile, serviceName stri
|
|||||||
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
|
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
|
||||||
args = append(args, "*", gfile.QualifiedGoIdent(method.Output.GoIdent))
|
args = append(args, "*", gfile.QualifiedGoIdent(method.Output.GoIdent))
|
||||||
} else {
|
} else {
|
||||||
args = append(args, serviceName, "_", method.GoName, "Client")
|
args = append(args, gfile.QualifiedGoIdent(protogen.GoIdent{GoName: serviceName + "_" + method.GoName + "Client", GoImportPath: method.Output.GoIdent.GoImportPath}))
|
||||||
}
|
}
|
||||||
args = append(args, ", error) {")
|
args = append(args, ", error) {")
|
||||||
gfile.P(args...)
|
gfile.P(args...)
|
||||||
@ -446,7 +596,7 @@ func generateClientSignature(gfile *protogen.GeneratedFile, serviceName string,
|
|||||||
gfile.P(args...)
|
gfile.P(args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateServiceClientInterface(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
func (g *Generator) generateServiceClientInterface(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
||||||
serviceName := service.GoName
|
serviceName := service.GoName
|
||||||
gfile.P("type ", serviceName, "Client interface {")
|
gfile.P("type ", serviceName, "Client interface {")
|
||||||
for _, method := range service.Methods {
|
for _, method := range service.Methods {
|
||||||
@ -456,7 +606,7 @@ func generateServiceClientInterface(gfile *protogen.GeneratedFile, service *prot
|
|||||||
gfile.P()
|
gfile.P()
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateServiceServerInterface(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
func (g *Generator) generateServiceServerInterface(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
||||||
serviceName := service.GoName
|
serviceName := service.GoName
|
||||||
gfile.P("type ", serviceName, "Server interface {")
|
gfile.P("type ", serviceName, "Server interface {")
|
||||||
for _, method := range service.Methods {
|
for _, method := range service.Methods {
|
||||||
@ -466,7 +616,7 @@ func generateServiceServerInterface(gfile *protogen.GeneratedFile, service *prot
|
|||||||
gfile.P()
|
gfile.P()
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateServiceClientStreamInterface(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
func (g *Generator) generateServiceClientStreamInterface(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
||||||
serviceName := service.GoName
|
serviceName := service.GoName
|
||||||
for _, method := range service.Methods {
|
for _, method := range service.Methods {
|
||||||
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
|
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
|
||||||
@ -478,10 +628,12 @@ func generateServiceClientStreamInterface(gfile *protogen.GeneratedFile, service
|
|||||||
gfile.P("SendMsg(msg interface{}) error")
|
gfile.P("SendMsg(msg interface{}) error")
|
||||||
gfile.P("RecvMsg(msg interface{}) error")
|
gfile.P("RecvMsg(msg interface{}) error")
|
||||||
if method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
|
if method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
|
||||||
gfile.P("RecvAndClose() (*", gfile.QualifiedGoIdent(method.Output.GoIdent), ", error)")
|
gfile.P("CloseAndRecv() (*", gfile.QualifiedGoIdent(method.Output.GoIdent), ", error)")
|
||||||
|
gfile.P("CloseSend() error")
|
||||||
}
|
}
|
||||||
gfile.P("Close() error")
|
gfile.P("Close() error")
|
||||||
if method.Desc.IsStreamingClient() {
|
if method.Desc.IsStreamingClient() {
|
||||||
|
gfile.P("Header() ", microMetadataPackage.Ident("Metadata"))
|
||||||
gfile.P("Send(msg *", gfile.QualifiedGoIdent(method.Input.GoIdent), ") error")
|
gfile.P("Send(msg *", gfile.QualifiedGoIdent(method.Input.GoIdent), ") error")
|
||||||
}
|
}
|
||||||
if method.Desc.IsStreamingServer() {
|
if method.Desc.IsStreamingServer() {
|
||||||
@ -492,7 +644,7 @@ func generateServiceClientStreamInterface(gfile *protogen.GeneratedFile, service
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateServiceServerStreamInterface(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
func (g *Generator) generateServiceServerStreamInterface(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
||||||
serviceName := service.GoName
|
serviceName := service.GoName
|
||||||
for _, method := range service.Methods {
|
for _, method := range service.Methods {
|
||||||
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
|
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
|
||||||
@ -505,6 +657,7 @@ func generateServiceServerStreamInterface(gfile *protogen.GeneratedFile, service
|
|||||||
gfile.P("RecvMsg(msg interface{}) error")
|
gfile.P("RecvMsg(msg interface{}) error")
|
||||||
if method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
|
if method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
|
||||||
gfile.P("SendAndClose(msg *", gfile.QualifiedGoIdent(method.Output.GoIdent), ") error")
|
gfile.P("SendAndClose(msg *", gfile.QualifiedGoIdent(method.Output.GoIdent), ") error")
|
||||||
|
// gfile.P("CloseSend() error")
|
||||||
}
|
}
|
||||||
gfile.P("Close() error")
|
gfile.P("Close() error")
|
||||||
if method.Desc.IsStreamingClient() {
|
if method.Desc.IsStreamingClient() {
|
||||||
@ -518,35 +671,6 @@ func generateServiceServerStreamInterface(gfile *protogen.GeneratedFile, service
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateServiceEndpoints(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
|
||||||
serviceName := service.GoName
|
|
||||||
gfile.P("var (")
|
|
||||||
gfile.P(serviceName, "Name", "=", `"`, serviceName, `"`)
|
|
||||||
gfile.P()
|
|
||||||
gfile.P(serviceName, "Endpoints", "=", "[]", microApiPackage.Ident("Endpoint"), "{")
|
|
||||||
for _, method := range service.Methods {
|
|
||||||
if method.Desc.Options() == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if proto.HasExtension(method.Desc.Options(), api_options.E_Http) {
|
|
||||||
endpoints, streaming := generateEndpoints(method)
|
|
||||||
for _, endpoint := range endpoints {
|
|
||||||
gfile.P("{")
|
|
||||||
generateEndpoint(gfile, serviceName, method.GoName, endpoint, streaming)
|
|
||||||
gfile.P("},")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
gfile.P("}")
|
|
||||||
gfile.P(")")
|
|
||||||
gfile.P()
|
|
||||||
|
|
||||||
gfile.P("func New", serviceName, "Endpoints()", "[]", microApiPackage.Ident("Endpoint"), "{")
|
|
||||||
gfile.P("return ", serviceName, "Endpoints")
|
|
||||||
gfile.P("}")
|
|
||||||
gfile.P()
|
|
||||||
}
|
|
||||||
|
|
||||||
func generateEndpoints(method *protogen.Method) ([]*api_options.HttpRule, bool) {
|
func generateEndpoints(method *protogen.Method) ([]*api_options.HttpRule, bool) {
|
||||||
if method.Desc.Options() == nil {
|
if method.Desc.Options() == nil {
|
||||||
return nil, false
|
return nil, false
|
||||||
@ -652,3 +776,268 @@ func generateEndpoint(gfile *protogen.GeneratedFile, serviceName string, methodN
|
|||||||
}
|
}
|
||||||
gfile.P(`Handler: "rpc",`)
|
gfile.P(`Handler: "rpc",`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (g *Generator) getGoIdentByXref(xref string) (protogen.GoIdent, error) {
|
||||||
|
idx := strings.LastIndex(xref, ".")
|
||||||
|
pkg := xref[:idx]
|
||||||
|
msg := xref[idx+1:]
|
||||||
|
for _, file := range g.plugin.Files {
|
||||||
|
if strings.Compare(pkg, *(file.Proto.Package)) != 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ident, err := getGoIdentByMessage(file.Messages, msg); err == nil {
|
||||||
|
return ident, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return protogen.GoIdent{}, fmt.Errorf("not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *Generator) getMessageByXref(xref string) (*protogen.Message, error) {
|
||||||
|
idx := strings.LastIndex(xref, ".")
|
||||||
|
pkg := xref[:idx]
|
||||||
|
msg := xref[idx+1:]
|
||||||
|
for _, file := range g.plugin.Files {
|
||||||
|
if strings.Compare(pkg, *(file.Proto.Package)) != 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if pmsg, err := getProtoMessage(file.Messages, msg); err == nil {
|
||||||
|
return pmsg, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProtoMessage(messages []*protogen.Message, msg string) (*protogen.Message, error) {
|
||||||
|
for _, message := range messages {
|
||||||
|
if strings.Compare(msg, message.GoIdent.GoName) == 0 {
|
||||||
|
return message, nil
|
||||||
|
}
|
||||||
|
if len(message.Messages) > 0 {
|
||||||
|
if pmsg, err := getProtoMessage(message.Messages, msg); err == nil {
|
||||||
|
return pmsg, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
func getGoIdentByMessage(messages []*protogen.Message, msg string) (protogen.GoIdent, error) {
|
||||||
|
for _, message := range messages {
|
||||||
|
if strings.Compare(msg, message.GoIdent.GoName) == 0 {
|
||||||
|
return message.GoIdent, nil
|
||||||
|
}
|
||||||
|
if len(message.Messages) > 0 {
|
||||||
|
if ident, err := getGoIdentByMessage(message.Messages, msg); err == nil {
|
||||||
|
return ident, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return protogen.GoIdent{}, fmt.Errorf("not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *Generator) generateServiceDesc(gfile *protogen.GeneratedFile, file *protogen.File, service *protogen.Service) {
|
||||||
|
serviceName := service.GoName
|
||||||
|
|
||||||
|
gfile.P("// ", serviceName, "_ServiceDesc", " is the ", grpcPackage.Ident("ServiceDesc"), " for ", serviceName, " service.")
|
||||||
|
gfile.P("// It's only intended for direct use with ", grpcPackage.Ident("RegisterService"), ",")
|
||||||
|
gfile.P("// and not to be introspected or modified (even as a copy)")
|
||||||
|
gfile.P("var ", serviceName, "_ServiceDesc", " = ", grpcPackage.Ident("ServiceDesc"), " {")
|
||||||
|
gfile.P("ServiceName: ", strconv.Quote(string(service.Desc.FullName())), ",")
|
||||||
|
gfile.P("HandlerType: (*", serviceName, "Server)(nil),")
|
||||||
|
gfile.P("Methods: []", grpcPackage.Ident("MethodDesc"), "{")
|
||||||
|
for _, method := range service.Methods {
|
||||||
|
if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
gfile.P("{")
|
||||||
|
gfile.P("MethodName: ", strconv.Quote(string(method.Desc.Name())), ",")
|
||||||
|
gfile.P("Handler: ", method.GoName, ",")
|
||||||
|
gfile.P("},")
|
||||||
|
}
|
||||||
|
gfile.P("},")
|
||||||
|
gfile.P("Streams: []", grpcPackage.Ident("StreamDesc"), "{")
|
||||||
|
for _, method := range service.Methods {
|
||||||
|
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
gfile.P("{")
|
||||||
|
gfile.P("StreamName: ", strconv.Quote(string(method.Desc.Name())), ",")
|
||||||
|
gfile.P("Handler: ", method.GoName, ",")
|
||||||
|
if method.Desc.IsStreamingServer() {
|
||||||
|
gfile.P("ServerStreams: true,")
|
||||||
|
}
|
||||||
|
if method.Desc.IsStreamingClient() {
|
||||||
|
gfile.P("ClientStreams: true,")
|
||||||
|
}
|
||||||
|
gfile.P("},")
|
||||||
|
}
|
||||||
|
gfile.P("},")
|
||||||
|
gfile.P("Metadata: \"", file.Desc.Path(), "\",")
|
||||||
|
gfile.P("}")
|
||||||
|
gfile.P()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *Generator) generateServiceName(gfile *protogen.GeneratedFile, service *protogen.Service) {
|
||||||
|
serviceName := service.GoName
|
||||||
|
gfile.P("var (")
|
||||||
|
gfile.P(serviceName, "Name", "=", `"`, serviceName, `"`)
|
||||||
|
gfile.P(")")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *Generator) generateServiceEndpoints(gfile *protogen.GeneratedFile, service *protogen.Service, component string) {
|
||||||
|
if component != "http" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
serviceName := service.GoName
|
||||||
|
|
||||||
|
gfile.P("var (")
|
||||||
|
gfile.P(serviceName, "ServerEndpoints = []", microServerHttpPackage.Ident("EndpointMetadata"), "{")
|
||||||
|
|
||||||
|
for _, method := range service.Methods {
|
||||||
|
if proto.HasExtension(method.Desc.Options(), api_options.E_Http) {
|
||||||
|
if endpoints, streaming := generateEndpoints(method); endpoints != nil {
|
||||||
|
for _, ep := range endpoints {
|
||||||
|
epath, emethod, ebody := getEndpoint(ep)
|
||||||
|
gfile.P("{")
|
||||||
|
gfile.P(`Name: "`, serviceName+"."+method.GoName, `",`)
|
||||||
|
gfile.P(`Path: "`, epath, `",`)
|
||||||
|
gfile.P(`Method: "`, emethod, `",`)
|
||||||
|
gfile.P(`Body: "`, ebody, `",`)
|
||||||
|
gfile.P(`Stream: `, streaming, `,`)
|
||||||
|
gfile.P("},")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
gfile.P("}")
|
||||||
|
gfile.P(")")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *Generator) writeErrors(plugin *protogen.Plugin) error {
|
||||||
|
errorsMap := make(map[string]struct{})
|
||||||
|
|
||||||
|
for _, file := range plugin.Files {
|
||||||
|
for _, service := range file.Services {
|
||||||
|
for _, method := range service.Methods {
|
||||||
|
if method.Desc.Options() != nil {
|
||||||
|
if proto.HasExtension(method.Desc.Options(), v2.E_Openapiv2Operation) {
|
||||||
|
opts := proto.GetExtension(method.Desc.Options(), v2.E_Openapiv2Operation)
|
||||||
|
if opts != nil {
|
||||||
|
r := opts.(*v2.Operation)
|
||||||
|
if r.Responses == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, rsp := range r.Responses.ResponseCode {
|
||||||
|
if schema := rsp.Value.GetJsonReference(); schema != nil {
|
||||||
|
xref := schema.XRef
|
||||||
|
if xref[0] == '.' {
|
||||||
|
xref = xref[1:]
|
||||||
|
}
|
||||||
|
if g.fileMessage(plugin.Files, xref) {
|
||||||
|
errorsMap[xref] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if proto.HasExtension(method.Desc.Options(), v3.E_Openapiv3Operation) {
|
||||||
|
opts := proto.GetExtension(method.Desc.Options(), v3.E_Openapiv3Operation)
|
||||||
|
if opts != nil {
|
||||||
|
r := opts.(*v3.Operation)
|
||||||
|
if r.Responses == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
resps := r.Responses.ResponseOrReference
|
||||||
|
if r.Responses.GetDefault() != nil {
|
||||||
|
resps = append(resps, &v3.NamedResponseOrReference{Name: "default", Value: r.Responses.GetDefault()})
|
||||||
|
}
|
||||||
|
for _, rsp := range resps {
|
||||||
|
if schema := rsp.Value.GetReference(); schema != nil {
|
||||||
|
xref := schema.XRef
|
||||||
|
if xref[0] == '.' {
|
||||||
|
xref = xref[1:]
|
||||||
|
}
|
||||||
|
if g.fileMessage(plugin.Files, xref) {
|
||||||
|
errorsMap[xref] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var gfile *protogen.GeneratedFile
|
||||||
|
var importPath protogen.GoImportPath
|
||||||
|
|
||||||
|
if len(errorsMap) > 0 {
|
||||||
|
|
||||||
|
var packageName string
|
||||||
|
|
||||||
|
for _, file := range plugin.Files {
|
||||||
|
if !file.Generate {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(file.Services) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
packageName = string(file.GoPackageName)
|
||||||
|
importPath = file.GoImportPath
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.standalone {
|
||||||
|
importPath = "."
|
||||||
|
}
|
||||||
|
|
||||||
|
gfile = plugin.NewGeneratedFile("micro_errors.pb.go", importPath)
|
||||||
|
|
||||||
|
gfile.P("// Code generated by protoc-gen-go-micro. DO NOT EDIT.")
|
||||||
|
gfile.P("// protoc-gen-go-micro version: " + versionComment)
|
||||||
|
gfile.P()
|
||||||
|
gfile.P("package ", packageName)
|
||||||
|
gfile.P()
|
||||||
|
|
||||||
|
gfile.Import(protojsonPackage)
|
||||||
|
|
||||||
|
gfile.P("var (")
|
||||||
|
gfile.P("marshaler = ", protojsonPackage.Ident("MarshalOptions"), "{}")
|
||||||
|
gfile.P(")")
|
||||||
|
}
|
||||||
|
|
||||||
|
for xref := range errorsMap {
|
||||||
|
msg, err := g.getMessageByXref(xref)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, field := range msg.Fields {
|
||||||
|
if field.GoName == "Error" {
|
||||||
|
return fmt.Errorf("failed generate Error() string interface for %s message %s already have Error field", field.Location.SourceFile, msg.Desc.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
gfile.P(`func (m *`, msg.GoIdent.GoName, `) Error() string {`)
|
||||||
|
gfile.P(`buf, _ := marshaler.Marshal(m)`)
|
||||||
|
gfile.P("return string(buf)")
|
||||||
|
gfile.P(`}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *Generator) fileMessage(files []*protogen.File, xref string) bool {
|
||||||
|
for _, file := range files {
|
||||||
|
for _, msg := range file.Messages {
|
||||||
|
if xref == string(msg.Desc.FullName()) && file.Generate {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
11
variables.go
11
variables.go
@ -3,6 +3,8 @@ package main
|
|||||||
import "google.golang.org/protobuf/compiler/protogen"
|
import "google.golang.org/protobuf/compiler/protogen"
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
ioPackage = protogen.GoImportPath("io")
|
||||||
|
graphqlPackage = protogen.GoImportPath("github.com/99designs/gqlgen/graphql")
|
||||||
reflectPackage = protogen.GoImportPath("reflect")
|
reflectPackage = protogen.GoImportPath("reflect")
|
||||||
stringsPackage = protogen.GoImportPath("strings")
|
stringsPackage = protogen.GoImportPath("strings")
|
||||||
fmtPackage = protogen.GoImportPath("fmt")
|
fmtPackage = protogen.GoImportPath("fmt")
|
||||||
@ -11,13 +13,16 @@ var (
|
|||||||
gorillaMuxPackage = protogen.GoImportPath("github.com/gorilla/mux")
|
gorillaMuxPackage = protogen.GoImportPath("github.com/gorilla/mux")
|
||||||
chiPackage = protogen.GoImportPath("github.com/go-chi/chi/v5")
|
chiPackage = protogen.GoImportPath("github.com/go-chi/chi/v5")
|
||||||
chiMiddlewarePackage = protogen.GoImportPath("github.com/go-chi/chi/v5/middleware")
|
chiMiddlewarePackage = protogen.GoImportPath("github.com/go-chi/chi/v5/middleware")
|
||||||
microApiPackage = protogen.GoImportPath("go.unistack.org/micro/v3/api")
|
microMetadataPackage = protogen.GoImportPath("go.unistack.org/micro/v3/metadata")
|
||||||
microClientPackage = protogen.GoImportPath("go.unistack.org/micro/v3/client")
|
microClientPackage = protogen.GoImportPath("go.unistack.org/micro/v3/client")
|
||||||
microServerPackage = protogen.GoImportPath("go.unistack.org/micro/v3/server")
|
microServerPackage = protogen.GoImportPath("go.unistack.org/micro/v3/server")
|
||||||
microClientHttpPackage = protogen.GoImportPath("go.unistack.org/micro-client-http/v3")
|
microClientHttpPackage = protogen.GoImportPath("go.unistack.org/micro-client-http/v3")
|
||||||
microServerHttpPackage = protogen.GoImportPath("go.unistack.org/micro-server-http/v3")
|
microServerHttpPackage = protogen.GoImportPath("go.unistack.org/micro-server-http/v3")
|
||||||
microCodecPackage = protogen.GoImportPath("go.unistack.org/micro/v3/codec")
|
microCodecPackage = protogen.GoImportPath("go.unistack.org/micro-proto/v3/codec")
|
||||||
|
microErrorsPackage = protogen.GoImportPath("go.unistack.org/micro/v3/errors")
|
||||||
|
grpcPackage = protogen.GoImportPath("google.golang.org/grpc")
|
||||||
|
protojsonPackage = protogen.GoImportPath("google.golang.org/protobuf/encoding/protojson")
|
||||||
timePackage = protogen.GoImportPath("time")
|
timePackage = protogen.GoImportPath("time")
|
||||||
deprecationComment = "// Deprecated: Do not use."
|
deprecationComment = "// Deprecated: Do not use."
|
||||||
versionComment = "v3.5.3"
|
versionComment = "v3.10.4"
|
||||||
)
|
)
|
||||||
|
Loading…
Reference in New Issue
Block a user