From 74907a453d856735f7af5b67e115f4f7739ff8d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 18:48:16 +0000 Subject: [PATCH] fix: rename path parameters that collide with generated names A path parameter whose Go name is one the generated method or handler uses itself, such as go-api-libs/ibkr's u, the request URL, no longer breaks the build: it is suffixed with Param, as are keywords and predeclared names, in the signature, the path, the server handler and api.js alike. The golden spec gains /portfolio/{u}/summary/{req}. The server's panic on a parameter inside a segment, which ibkr's path also has, goes on the roadmap. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017Pd6RdtkAJq4fCsH7CzhRx --- docs/roadmap.md | 9 ++++ ir/operation.go | 31 ++++++++++++- testdata/golden/api/openapi.json | 29 +++++++++++++ testdata/golden/pkg/golden/api.js | 5 +++ testdata/golden/pkg/golden/client.gen.go | 38 ++++++++++++++++ testdata/golden/pkg/golden/client.gen_test.go | 41 ++++++++++++++++++ testdata/golden/pkg/golden/ir.json | 43 +++++++++++++++++++ testdata/golden/pkg/golden/path_test.go | 9 ++++ testdata/golden/pkg/golden/server.gen.go | 38 ++++++++++++++++ 9 files changed, 242 insertions(+), 1 deletion(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index 17dd1bc8..d40c6d90 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -44,3 +44,12 @@ custom format, `date-time-ms`, like `date-basic`, makes them a `time.Time` in milliseconds, written and read through jsonutil helpers beside `TimeMarshalIntUnix`, in a body and a query parameter alike. openapi-enrich must keep the format when a recording's integer meets it. + +## Server routes for a parameter inside a segment + +A path parameter can share its segment with fixed text, as go-api-libs/ibkr's +`/portfolio/U{u}/summary` and sec's `/api/xbrl/companyfacts/CIK{cik}.json` do. +The client builds such a path, but `RegisterService` hands the template to +`http.ServeMux` as it is, and a wildcard there must be the whole segment, so +registering the service panics. The server would route the whole segment and +strip the fixed text itself, answering 404 where it is missing. diff --git a/ir/operation.go b/ir/operation.go index 6076fbd6..1b52cf8d 100644 --- a/ir/operation.go +++ b/ir/operation.go @@ -5,6 +5,8 @@ import ( "encoding/json/jsontext" "encoding/json/v2" "fmt" + "go/token" + "go/types" "net/http" "net/url" "slices" @@ -276,6 +278,10 @@ func fromParam(p *openapi.Parameter, apiTitle string) (Param, error) { } param.GoName = strcase.ToGoCamel(p.Name) + if p.In == openapi.ParameterLocationPath { + param.GoName = pathParamName(p.Name) + } + param.AllowSlashes = p.In == openapi.ParameterLocationPath && allowsSlashes(p) param.FieldName = goPascal(p.Name) @@ -335,7 +341,7 @@ func fromParam(p *openapi.Parameter, apiTitle string) (Param, error) { if param.VarName == "" { if p.In == openapi.ParameterLocationPath { - param.VarName = strcase.ToGoCamel(p.Name) + param.VarName = param.GoName } else { param.VarName = "params." + param.FieldName } @@ -407,6 +413,29 @@ func parseExpr(goType string, unixTime bool) (expr, conv string, errFree bool) { } } +// generatedNames are the identifiers the generated code refers to where a path parameter is in scope: the locals of +// the client's methods and the server's handlers, the packages they use and the client's receiver. +var generatedNames = map[string]bool{ + "api": true, "body": true, "c": true, "civil": true, "cmp": true, "context": true, "ctx": true, "cursor": true, + "errors": true, "escaped": true, "fmt": true, "http": true, "i": true, "ia": true, "io": true, "iter": true, + "json": true, "l": true, "maps": true, "msg": true, "mt": true, "net": true, "ok": true, "out": true, + "paging": true, "params": true, "parts": true, "pr": true, "pw": true, "q": true, + "r": true, "req": true, "res": true, "rsp": true, "sErr": true, "server": true, "slices": true, "slog": true, + "strconv": true, "streaming": true, "strings": true, "svc": true, "time": true, "u": true, "url": true, + "uuid": true, "v": true, "w": true, +} + +// pathParamName is the Go identifier of the path parameter named name, which the generated method takes as an +// argument: suffixed where it would collide with a keyword, a predeclared name or one of generatedNames. +func pathParamName(name string) string { + id := strcase.ToGoCamel(name) + if generatedNames[id] || token.IsKeyword(id) || types.Universe.Lookup(id) != nil { + return id + "Param" + } + + return id +} + // buildJoinPathArgs produces the ordered list of Go expressions for url.JoinPath. // e.g. "/apis/{id}/items" → [`"apis"`, `strconv.Itoa(id)`, `"items"`] func buildJoinPathArgs(parsed openapi.ParsedPath, params map[string]Param) []string { diff --git a/testdata/golden/api/openapi.json b/testdata/golden/api/openapi.json index da8c2738..b33fea19 100644 --- a/testdata/golden/api/openapi.json +++ b/testdata/golden/api/openapi.json @@ -765,6 +765,35 @@ } } }, + "/portfolio/{u}/summary/{req}": { + "get": { + "operationId": "getPortfolioSummary", + "description": "Path parameters named as the generated code's own variables are renamed.", + "parameters": [ + { + "name": "u", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "req", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "no content" + } + } + } + }, "/ranges": { "get": { "operationId": "getRanges", diff --git a/testdata/golden/pkg/golden/api.js b/testdata/golden/pkg/golden/api.js index 05d54ae0..670a0e82 100644 --- a/testdata/golden/pkg/golden/api.js +++ b/testdata/golden/pkg/golden/api.js @@ -27,6 +27,7 @@ * const result = await window.API.downloadReport(format); * window.API.deleteSchedule(id); * window.API.getFile(path); + * window.API.getPortfolioSummary(uParam, reqParam); * const result = await window.API.getRanges(); * const result = await window.API.getStatus(); * window.API.queryStyles(page); @@ -217,6 +218,10 @@ window.API = { getFile: (path) => apiFetch(`/files/${path}`, { operationId: "GetFile", }), + // GET /portfolio/{u}/summary/{req} + getPortfolioSummary: (uParam, reqParam) => apiFetch(`/portfolio/${uParam}/summary/${reqParam}`, { + operationId: "GetPortfolioSummary", + }), // GET /ranges getRanges: () => apiFetch("/ranges", { operationId: "GetRanges", diff --git a/testdata/golden/pkg/golden/client.gen.go b/testdata/golden/pkg/golden/client.gen.go index 969a7fdb..de9d995e 100644 --- a/testdata/golden/pkg/golden/client.gen.go +++ b/testdata/golden/pkg/golden/client.gen.go @@ -1037,6 +1037,44 @@ func (c *Client) GetFile(ctx context.Context, path string) error { } } +// Path parameters named as the generated code's own variables are renamed. +// +// GET /portfolio/{u}/summary/{req} +func (c *Client) GetPortfolioSummary(ctx context.Context, uParam string, reqParam string) error { + u := c.baseURL.JoinPath("portfolio", escapePathSegment(uParam), "summary", escapePathSegment(reqParam)) + req := (&http.Request{ + Header: http.Header{ + "User-Agent": []string{c.userAgent}, + }, + Host: u.Host, + Method: http.MethodGet, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + URL: u, + }).WithContext(ctx) + + rsp, err := c.cli.Do(req) + if err != nil { + return err + } + defer rsp.Body.Close() + + switch rsp.StatusCode { + case http.StatusNoContent: + // no content + switch mt, _, _ := strings.Cut(rsp.Header.Get("Content-Type"), ";"); mt { + case "": + + return nil + default: + return api.NewErrUnknownContentType(rsp) + } + default: + return api.NewErrUnknownStatusCode(rsp) + } +} + // A range of codes, matched after the exact codes, which take precedence over it. // // GET /ranges diff --git a/testdata/golden/pkg/golden/client.gen_test.go b/testdata/golden/pkg/golden/client.gen_test.go index 72126b74..0536d487 100644 --- a/testdata/golden/pkg/golden/client.gen_test.go +++ b/testdata/golden/pkg/golden/client.gen_test.go @@ -1917,6 +1917,47 @@ func TestClient_Error(t *testing.T) { }) }) + t.Run("GetPortfolioSummary", func(t *testing.T) { + t.Run("transport error", func(t *testing.T) { + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( + func(*http.Request) (*http.Response, error) { return nil, io.EOF }, + )})) + if err != nil { + t.Fatal(err) + } + + if err := c.GetPortfolioSummary(t.Context(), "", ""); err == nil { + t.Fatal("expected error") + } else if !errors.Is(err, io.EOF) { + t.Fatalf("want: %v, got: %v", io.EOF, err) + } + }) + + t.Run("unknown status code", func(t *testing.T) { + srv := apitest.NewServer(t, http.StatusTeapot) + + baseURL, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(baseURL)) + if err != nil { + t.Fatal(err) + } + + if err := c.GetPortfolioSummary(t.Context(), "", ""); err == nil { + t.Fatal("expected error") + } else if apiErr, ok := errors.AsType[*api.Error](err); !ok { + t.Fatalf("got: %T, want: *api.Error", err) + } else if apiErr.Err != api.ErrUnknownStatusCode { + t.Fatalf("got: %v, want: %v", apiErr.Err, api.ErrUnknownStatusCode) + } else if apiErr.Response.StatusCode != http.StatusTeapot { + t.Fatalf("got: %v, want: %v", apiErr.Response.StatusCode, http.StatusTeapot) + } + }) + }) + t.Run("GetRanges", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( diff --git a/testdata/golden/pkg/golden/ir.json b/testdata/golden/pkg/golden/ir.json index ee7d9d6f..e17da94e 100644 --- a/testdata/golden/pkg/golden/ir.json +++ b/testdata/golden/pkg/golden/ir.json @@ -852,6 +852,49 @@ } ] }, + { + "name": "GetPortfolioSummary", + "description": "Path parameters named as the generated code's own variables are renamed.", + "method": "GET", + "pathTemplate": "/portfolio/{u}/summary/{req}", + "joinPathArgs": [ + "\"portfolio\"", + "escapePathSegment(uParam)", + "\"summary\"", + "escapePathSegment(reqParam)" + ], + "pathParams": [ + { + "varName": "uParam", + "goName": "uParam", + "fieldName": "U", + "jsonName": "u", + "type": "string", + "required": true, + "parseExpr": "%s", + "parseErrFree": true + }, + { + "varName": "reqParam", + "goName": "reqParam", + "fieldName": "Req", + "jsonName": "req", + "type": "string", + "required": true, + "parseExpr": "%s", + "parseErrFree": true + } + ], + "hasParams": true, + "responses": [ + { + "statusCode": "204", + "goConstant": "http.StatusNoContent", + "description": "no content", + "isSuccess": true + } + ] + }, { "name": "GetRanges", "description": "A range of codes, matched after the exact codes, which take precedence over it.", diff --git a/testdata/golden/pkg/golden/path_test.go b/testdata/golden/pkg/golden/path_test.go index ee835416..f3858fd7 100644 --- a/testdata/golden/pkg/golden/path_test.go +++ b/testdata/golden/pkg/golden/path_test.go @@ -110,3 +110,12 @@ func TestPath_KeepsSlashes(t *testing.T) { }) } } + +// TestPath_RenamesParameters sends path parameters named u and req, as the method's own variables are: they are taken +// as uParam and reqParam, so the method still compiles and builds its URL from them. +func TestPath_RenamesParameters(t *testing.T) { + const want = "/v1/portfolio/U1234/summary/r1" + if got := sentPath(t, func(c *Client) error { return c.GetPortfolioSummary(t.Context(), "U1234", "r1") }); got != want { + t.Errorf("sent to %s, want %s", got, want) + } +} diff --git a/testdata/golden/pkg/golden/server.gen.go b/testdata/golden/pkg/golden/server.gen.go index ab2f0080..9ac77c82 100644 --- a/testdata/golden/pkg/golden/server.gen.go +++ b/testdata/golden/pkg/golden/server.gen.go @@ -41,6 +41,7 @@ type Service interface { DownloadReport(ctx context.Context, format ScheduleFormat) (io.ReadCloser, error) DeleteSchedule(ctx context.Context, id string) error GetFile(ctx context.Context, path string) error + GetPortfolioSummary(ctx context.Context, uParam string, reqParam string) error GetRanges(ctx context.Context) ([]string, error) GetStatus(ctx context.Context) ([]byte, error) QueryStyles(ctx context.Context, page int, params QueryStylesParams) error @@ -881,6 +882,43 @@ func RegisterService(svc Service, mux *http.ServeMux, pathPrefix string) { }) } + { + path := fmt.Sprintf("%s%s", pathPrefix, "/portfolio/{u}/summary/{req}") + l := slog.Default().With(slog.String("method", "GET"), slog.String("path", path), slog.String("function", "GetPortfolioSummary")) + + mux.HandleFunc(fmt.Sprintf("GET %s", path), func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + l.DebugContext(ctx, "called") + + uParam := r.PathValue("u") + reqParam := r.PathValue("req") + + if err := svc.GetPortfolioSummary(ctx, uParam, reqParam); err != nil { + sErr, ok := errors.AsType[*server.Error](err) + if !ok { + l.ErrorContext(ctx, "Internal Server Error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + l.DebugContext(ctx, "graceful error", slog.String("error", err.Error())) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(sErr.Code) + + if err := json.MarshalWrite(w, err); err != nil { + l.ErrorContext(ctx, "marshal error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } + return + } + + w.WriteHeader(http.StatusNoContent) + + l.DebugContext(ctx, "success") + }) + } + { path := fmt.Sprintf("%s%s", pathPrefix, "/ranges") l := slog.Default().With(slog.String("method", "GET"), slog.String("path", path), slog.String("function", "GetRanges"))