Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ 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.

## More of oapi-codegen's extensions

`x-go-name` and `x-enum-varnames` / `x-enumNames` work as in
Expand Down
31 changes: 30 additions & 1 deletion ir/operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"encoding/json/jsontext"
"encoding/json/v2"
"fmt"
"go/token"
"go/types"
"net/http"
"net/url"
"slices"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 {
Expand Down
29 changes: 29 additions & 0 deletions testdata/golden/api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
5 changes: 5 additions & 0 deletions testdata/golden/pkg/golden/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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",
Expand Down
38 changes: 38 additions & 0 deletions testdata/golden/pkg/golden/client.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 41 additions & 0 deletions testdata/golden/pkg/golden/client.gen_test.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

43 changes: 43 additions & 0 deletions testdata/golden/pkg/golden/ir.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
9 changes: 9 additions & 0 deletions testdata/golden/pkg/golden/path_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
38 changes: 38 additions & 0 deletions testdata/golden/pkg/golden/server.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading