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
59 changes: 59 additions & 0 deletions packages/go-parser/src/__tests__/route-path-join.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { describe, test, expect } from "@jest/globals"
import { extractRoutes, joinPaths, type GoSourceFile } from "../route-parser.js"

// Gin joins a group's prefix and a route's path with path.Join, so slashes are
// optional on either side: Group("api").Group("v1").POST("device") serves
// /api/v1/device. Plain concatenation produced "apiv1device".

const file = (content: string): GoSourceFile => ({ path: "main.go", content })
const paths = (content: string) => extractRoutes([file(content)]).map((r) => `${r.method} ${r.path}`)

describe("joinPaths", () => {
test.each([
["", "", ""],
["", "/", "/"],
["", "api", "/api"],
["/api", "v1", "/api/v1"],
["/api/", "/v1", "/api/v1"],
["/api", "", "/api"],
["/api", "/", "/api/"],
["/api", "users/", "/api/users/"],
["/api", "//users", "/api/users"],
["/api", ":id", "/api/:id"],
["/files", "*filepath", "/files/*filepath"],
])("joinPaths(%j, %j) = %j", (base, relative, expected) => {
expect(joinPaths(base, relative)).toBe(expected)
})
})

describe("route paths built from groups without slashes", () => {
test("groups and routes written without leading slashes", () => {
expect(paths(`package main
func main() {
r := gin.Default()
api := r.Group("api")
v1 := api.Group("v1")
device := v1.Group("device")
device.POST("", create)
device.GET(":id", get)
device.GET("detail/:id", detail)
}`)).toEqual(["POST /api/v1/device", "GET /api/v1/device/:id", "GET /api/v1/device/detail/:id"])
})

test("a trailing slash on the group does not double up", () => {
expect(paths(`package main
func main() {
r := gin.Default()
api := r.Group("/api/")
api.GET("/users", list)
}`)).toEqual(["GET /api/users"])
})

test("a route on the engine with an empty path is /", () => {
expect(paths(`package main
func main() {
r := gin.Default()
r.GET("", home)
}`)).toEqual(["GET /"])
})
})
17 changes: 14 additions & 3 deletions packages/go-parser/src/route-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export interface MiddlewareRef {

export interface RouteInfo {
method: string
/** Fully resolved path — concatenation of every enclosing Group() prefix. */
/** Fully resolved path — every enclosing Group() prefix joined the way Gin joins them. */
path: string
/** Raw text of the final (handler) argument, e.g. "handler.CreateOrder". */
handlerText: string
Expand Down Expand Up @@ -170,7 +170,18 @@ function groupOf(expr: SyntaxNode, file: string, groups: Map<string, GroupState>
const refs = (nodes: SyntaxNode[]): MiddlewareRef[] => nodes.map((a) => toMiddlewareRef(a, file)).filter((m): m is MiddlewareRef => !!m)
if (method === "Use") return { ...base, middleware: [...base.middleware, ...refs(args)] }
const [pathArg, ...mwArgs] = args
return { prefix: base.prefix + (pathArg ? stringLiteralValue(pathArg) ?? "" : ""), middleware: [...base.middleware, ...refs(mwArgs)] }
return { prefix: joinPaths(base.prefix, pathArg ? stringLiteralValue(pathArg) ?? "" : ""), middleware: [...base.middleware, ...refs(mwArgs)] }
}

/**
* Gin's joinPaths: `path.Join(base, relative)`, keeping a trailing slash the
* relative path has. `Group("api").Group("v1").POST("device")` is /api/v1/device,
* and `Group("/api/").GET("/x")` is /api/x — not a plain concatenation.
*/
export function joinPaths(base: string, relative: string): string {
if (relative === "") return base
const joined = "/" + [...base.split("/"), ...relative.split("/")].filter((s) => s !== "" && s !== ".").join("/")
return relative.endsWith("/") && !joined.endsWith("/") ? `${joined}/` : joined
}

/**
Expand Down Expand Up @@ -313,7 +324,7 @@ function handleStatement(

routes.push({
method: parts.method,
path: state.prefix + suffix,
path: joinPaths(state.prefix, suffix) || "/",
handlerText: handlerArg.text,
handlerReceiverType: handlerReceiverType(handlerArg, paramTypes),
middleware: [...state.middleware, ...inlineMw],
Expand Down
Loading