Skip to content

Commit aeeae2d

Browse files
Merge pull request #88 from MarkRosemaker/fix/path-param-names
fix: rename path parameters that collide with generated names
2 parents 09697b4 + 01bf027 commit aeeae2d

9 files changed

Lines changed: 242 additions & 1 deletion

File tree

‎docs/roadmap.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,15 @@ milliseconds, written and read through jsonutil helpers beside
4545
`TimeMarshalIntUnix`, in a body and a query parameter alike. openapi-enrich
4646
must keep the format when a recording's integer meets it.
4747

48+
## Server routes for a parameter inside a segment
49+
50+
A path parameter can share its segment with fixed text, as go-api-libs/ibkr's
51+
`/portfolio/U{u}/summary` and sec's `/api/xbrl/companyfacts/CIK{cik}.json` do.
52+
The client builds such a path, but `RegisterService` hands the template to
53+
`http.ServeMux` as it is, and a wildcard there must be the whole segment, so
54+
registering the service panics. The server would route the whole segment and
55+
strip the fixed text itself, answering 404 where it is missing.
56+
4857
## More of oapi-codegen's extensions
4958

5059
`x-go-name` and `x-enum-varnames` / `x-enumNames` work as in

‎ir/operation.go‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"encoding/json/jsontext"
66
"encoding/json/v2"
77
"fmt"
8+
"go/token"
9+
"go/types"
810
"net/http"
911
"net/url"
1012
"slices"
@@ -276,6 +278,10 @@ func fromParam(p *openapi.Parameter, apiTitle string) (Param, error) {
276278
}
277279

278280
param.GoName = strcase.ToGoCamel(p.Name)
281+
if p.In == openapi.ParameterLocationPath {
282+
param.GoName = pathParamName(p.Name)
283+
}
284+
279285
param.AllowSlashes = p.In == openapi.ParameterLocationPath && allowsSlashes(p)
280286

281287
param.FieldName = goPascal(p.Name)
@@ -335,7 +341,7 @@ func fromParam(p *openapi.Parameter, apiTitle string) (Param, error) {
335341

336342
if param.VarName == "" {
337343
if p.In == openapi.ParameterLocationPath {
338-
param.VarName = strcase.ToGoCamel(p.Name)
344+
param.VarName = param.GoName
339345
} else {
340346
param.VarName = "params." + param.FieldName
341347
}
@@ -407,6 +413,29 @@ func parseExpr(goType string, unixTime bool) (expr, conv string, errFree bool) {
407413
}
408414
}
409415

416+
// generatedNames are the identifiers the generated code refers to where a path parameter is in scope: the locals of
417+
// the client's methods and the server's handlers, the packages they use and the client's receiver.
418+
var generatedNames = map[string]bool{
419+
"api": true, "body": true, "c": true, "civil": true, "cmp": true, "context": true, "ctx": true, "cursor": true,
420+
"errors": true, "escaped": true, "fmt": true, "http": true, "i": true, "ia": true, "io": true, "iter": true,
421+
"json": true, "l": true, "maps": true, "msg": true, "mt": true, "net": true, "ok": true, "out": true,
422+
"paging": true, "params": true, "parts": true, "pr": true, "pw": true, "q": true,
423+
"r": true, "req": true, "res": true, "rsp": true, "sErr": true, "server": true, "slices": true, "slog": true,
424+
"strconv": true, "streaming": true, "strings": true, "svc": true, "time": true, "u": true, "url": true,
425+
"uuid": true, "v": true, "w": true,
426+
}
427+
428+
// pathParamName is the Go identifier of the path parameter named name, which the generated method takes as an
429+
// argument: suffixed where it would collide with a keyword, a predeclared name or one of generatedNames.
430+
func pathParamName(name string) string {
431+
id := strcase.ToGoCamel(name)
432+
if generatedNames[id] || token.IsKeyword(id) || types.Universe.Lookup(id) != nil {
433+
return id + "Param"
434+
}
435+
436+
return id
437+
}
438+
410439
// buildJoinPathArgs produces the ordered list of Go expressions for url.JoinPath.
411440
// e.g. "/apis/{id}/items" → [`"apis"`, `strconv.Itoa(id)`, `"items"`]
412441
func buildJoinPathArgs(parsed openapi.ParsedPath, params map[string]Param) []string {

‎testdata/golden/api/openapi.json‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -765,6 +765,35 @@
765765
}
766766
}
767767
},
768+
"/portfolio/{u}/summary/{req}": {
769+
"get": {
770+
"operationId": "getPortfolioSummary",
771+
"description": "Path parameters named as the generated code's own variables are renamed.",
772+
"parameters": [
773+
{
774+
"name": "u",
775+
"in": "path",
776+
"required": true,
777+
"schema": {
778+
"type": "string"
779+
}
780+
},
781+
{
782+
"name": "req",
783+
"in": "path",
784+
"required": true,
785+
"schema": {
786+
"type": "string"
787+
}
788+
}
789+
],
790+
"responses": {
791+
"204": {
792+
"description": "no content"
793+
}
794+
}
795+
}
796+
},
768797
"/ranges": {
769798
"get": {
770799
"operationId": "getRanges",

‎testdata/golden/pkg/golden/api.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
* const result = await window.API.downloadReport(format);
2828
* window.API.deleteSchedule(id);
2929
* window.API.getFile(path);
30+
* window.API.getPortfolioSummary(uParam, reqParam);
3031
* const result = await window.API.getRanges();
3132
* const result = await window.API.getStatus();
3233
* window.API.queryStyles(page);
@@ -217,6 +218,10 @@ window.API = {
217218
getFile: (path) => apiFetch(`/files/${path}`, {
218219
operationId: "GetFile",
219220
}),
221+
// GET /portfolio/{u}/summary/{req}
222+
getPortfolioSummary: (uParam, reqParam) => apiFetch(`/portfolio/${uParam}/summary/${reqParam}`, {
223+
operationId: "GetPortfolioSummary",
224+
}),
220225
// GET /ranges
221226
getRanges: () => apiFetch("/ranges", {
222227
operationId: "GetRanges",

‎testdata/golden/pkg/golden/client.gen.go‎

Lines changed: 38 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎testdata/golden/pkg/golden/client.gen_test.go‎

Lines changed: 41 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎testdata/golden/pkg/golden/ir.json‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -852,6 +852,49 @@
852852
}
853853
]
854854
},
855+
{
856+
"name": "GetPortfolioSummary",
857+
"description": "Path parameters named as the generated code's own variables are renamed.",
858+
"method": "GET",
859+
"pathTemplate": "/portfolio/{u}/summary/{req}",
860+
"joinPathArgs": [
861+
"\"portfolio\"",
862+
"escapePathSegment(uParam)",
863+
"\"summary\"",
864+
"escapePathSegment(reqParam)"
865+
],
866+
"pathParams": [
867+
{
868+
"varName": "uParam",
869+
"goName": "uParam",
870+
"fieldName": "U",
871+
"jsonName": "u",
872+
"type": "string",
873+
"required": true,
874+
"parseExpr": "%s",
875+
"parseErrFree": true
876+
},
877+
{
878+
"varName": "reqParam",
879+
"goName": "reqParam",
880+
"fieldName": "Req",
881+
"jsonName": "req",
882+
"type": "string",
883+
"required": true,
884+
"parseExpr": "%s",
885+
"parseErrFree": true
886+
}
887+
],
888+
"hasParams": true,
889+
"responses": [
890+
{
891+
"statusCode": "204",
892+
"goConstant": "http.StatusNoContent",
893+
"description": "no content",
894+
"isSuccess": true
895+
}
896+
]
897+
},
855898
{
856899
"name": "GetRanges",
857900
"description": "A range of codes, matched after the exact codes, which take precedence over it.",

‎testdata/golden/pkg/golden/path_test.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,3 +110,12 @@ func TestPath_KeepsSlashes(t *testing.T) {
110110
})
111111
}
112112
}
113+
114+
// TestPath_RenamesParameters sends path parameters named u and req, as the method's own variables are: they are taken
115+
// as uParam and reqParam, so the method still compiles and builds its URL from them.
116+
func TestPath_RenamesParameters(t *testing.T) {
117+
const want = "/v1/portfolio/U1234/summary/r1"
118+
if got := sentPath(t, func(c *Client) error { return c.GetPortfolioSummary(t.Context(), "U1234", "r1") }); got != want {
119+
t.Errorf("sent to %s, want %s", got, want)
120+
}
121+
}

‎testdata/golden/pkg/golden/server.gen.go‎

Lines changed: 38 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)