Skip to content

Commit

Permalink
make TemplateName fields private
Browse files Browse the repository at this point in the history
  • Loading branch information
crhntr committed Aug 19, 2024
1 parent 1df23cf commit 86332a6
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 63 deletions.
6 changes: 3 additions & 3 deletions generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,15 +122,15 @@ func (def TemplateName) callHandleFunc(handlerFuncLit *ast.FuncLit) *ast.ExprStm
Args: []ast.Expr{
&ast.BasicLit{
Kind: token.STRING,
Value: strconv.Quote(def.Route),
Value: strconv.Quote(def.endpoint),
},
handlerFuncLit,
},
}}
}

func (def TemplateName) funcLit(templatesVariableIdent string, method *ast.FuncType) (*ast.FuncLit, []*ast.ImportSpec, error) {
if def.Handler == "" {
if def.handler == "" {
return def.httpRequestReceiverTemplateHandlerFunc(templatesVariableIdent), nil, nil
}
lit := &ast.FuncLit{
Expand Down Expand Up @@ -255,7 +255,7 @@ func fieldListTypes(fieldList *ast.FieldList) func(func(int, ast.Expr) bool) {
}

func errWrongNumberOfArguments(def TemplateName, method *ast.FuncType) error {
return fmt.Errorf("handler %s expects %d arguments but call %s has %d", source.Format(&ast.FuncDecl{Name: ast.NewIdent(def.fun.Name), Type: method}), method.Params.NumFields(), def.Handler, len(def.call.Args))
return fmt.Errorf("handler %s expects %d arguments but call %s has %d", source.Format(&ast.FuncDecl{Name: ast.NewIdent(def.fun.Name), Type: method}), method.Params.NumFields(), def.handler, len(def.call.Args))
}

func checkArgument(exp ast.Expr, tp ast.Expr) error {
Expand Down
50 changes: 26 additions & 24 deletions pattern.go → name.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,20 +26,20 @@ func TemplateNames(ts *template.Template) ([]TemplateName, error) {
if err != nil {
return templateNames, err
}
if _, exists := routes[pat.Method+pat.Path]; exists {
return templateNames, fmt.Errorf("duplicate route pattern: %s", pat.Route)
if _, exists := routes[pat.method+pat.path]; exists {
return templateNames, fmt.Errorf("duplicate route pattern: %s", pat.endpoint)
}
routes[pat.Method+pat.Path] = struct{}{}
routes[pat.method+pat.path] = struct{}{}
templateNames = append(templateNames, pat)
}
slices.SortFunc(templateNames, TemplateName.byPathThenMethod)
return templateNames, nil
}

type TemplateName struct {
name string
Method, Host, Path, Route string
Handler string
name string
method, host, path, endpoint string
handler string

fun *ast.Ident
call *ast.CallExpr
Expand All @@ -53,17 +53,17 @@ func NewTemplateName(in string) (TemplateName, error, bool) {
}
matches := templateNameMux.FindStringSubmatch(in)
p := TemplateName{
name: in,
Method: matches[templateNameMux.SubexpIndex("Method")],
Host: matches[templateNameMux.SubexpIndex("Host")],
Path: matches[templateNameMux.SubexpIndex("Path")],
Handler: strings.TrimSpace(matches[templateNameMux.SubexpIndex("Handler")]),
Route: matches[templateNameMux.SubexpIndex("Route")],
name: in,
method: matches[templateNameMux.SubexpIndex("method")],
host: matches[templateNameMux.SubexpIndex("host")],
path: matches[templateNameMux.SubexpIndex("path")],
handler: strings.TrimSpace(matches[templateNameMux.SubexpIndex("handler")]),
endpoint: matches[templateNameMux.SubexpIndex("endpoint")],
}

switch p.Method {
switch p.method {
default:
return p, fmt.Errorf("%s method not allowed", p.Method), true
return p, fmt.Errorf("%s method not allowed", p.method), true
case "", http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
}

Expand All @@ -81,14 +81,14 @@ func NewTemplateName(in string) (TemplateName, error, bool) {

var (
pathSegmentPattern = regexp.MustCompile(`/\{([^}]*)}`)
templateNameMux = regexp.MustCompile(`^(?P<Route>(((?P<Method>[A-Z]+)\s+)?)(?P<Host>([^/])*)(?P<Path>(/(\S)*)))(?P<Handler>.*)$`)
templateNameMux = regexp.MustCompile(`^(?P<endpoint>(((?P<method>[A-Z]+)\s+)?)(?P<host>([^/])*)(?P<path>(/(\S)*)))(?P<handler>.*)$`)
)

func (def TemplateName) parsePathValueNames() ([]string, error) {
var result []string
for _, match := range pathSegmentPattern.FindAllStringSubmatch(def.Path, strings.Count(def.Path, "/")) {
for _, match := range pathSegmentPattern.FindAllStringSubmatch(def.path, strings.Count(def.path, "/")) {
n := match[1]
if n == "$" && strings.Count(def.Path, "$") == 1 && strings.HasSuffix(def.Path, "{$}") {
if n == "$" && strings.Count(def.path, "$") == 1 && strings.HasSuffix(def.path, "{$}") {
continue
}
n = strings.TrimSuffix(n, "...")
Expand All @@ -112,24 +112,26 @@ func checkPathValueNames(in []string) error {
return nil
}

func (def TemplateName) String() string { return def.name }
func (def TemplateName) sameRoute(p TemplateName) bool { return def.Route == p.Route }
func (def TemplateName) String() string { return def.name }
func (def TemplateName) Pattern() string { return def.method + " " + def.path }

func (def TemplateName) sameRoute(p TemplateName) bool { return def.endpoint == p.endpoint }

func (def TemplateName) byPathThenMethod(d TemplateName) int {
if n := cmp.Compare(def.Path, d.Path); n != 0 {
if n := cmp.Compare(def.path, d.path); n != 0 {
return n
}
if m := cmp.Compare(def.Method, d.Method); m != 0 {
if m := cmp.Compare(def.method, d.method); m != 0 {
return m
}
return cmp.Compare(def.Handler, d.Handler)
return cmp.Compare(def.handler, d.handler)
}

func parseHandler(def *TemplateName) error {
if def.Handler == "" {
if def.handler == "" {
return nil
}
e, err := parser.ParseExpr(def.Handler)
e, err := parser.ParseExpr(def.handler)
if err != nil {
return fmt.Errorf("failed to parse handler expression: %v", err)
}
Expand Down
72 changes: 36 additions & 36 deletions pattern_test.go → name_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ func TestNewTemplateName(t *testing.T) {
ExpMatch: true,
TemplateName: func(t *testing.T, pat muxt.TemplateName) {
assert.EqualExportedValues(t, muxt.TemplateName{
Method: http.MethodGet,
Host: "",
Path: "/",
Route: "GET /",
Handler: "",
method: http.MethodGet,

Check failure on line 41 in name_test.go

View workflow job for this annotation

GitHub Actions / build

cannot refer to unexported field method in struct literal of type muxt.TemplateName
host: "",

Check failure on line 42 in name_test.go

View workflow job for this annotation

GitHub Actions / build

cannot refer to unexported field host in struct literal of type muxt.TemplateName
path: "/",

Check failure on line 43 in name_test.go

View workflow job for this annotation

GitHub Actions / build

cannot refer to unexported field path in struct literal of type muxt.TemplateName
endpoint: "GET /",

Check failure on line 44 in name_test.go

View workflow job for this annotation

GitHub Actions / build

cannot refer to unexported field endpoint in struct literal of type muxt.TemplateName
handler: "",

Check failure on line 45 in name_test.go

View workflow job for this annotation

GitHub Actions / build

cannot refer to unexported field handler in struct literal of type muxt.TemplateName
}, pat)
},
},
Expand All @@ -52,11 +52,11 @@ func TestNewTemplateName(t *testing.T) {
ExpMatch: true,
TemplateName: func(t *testing.T, pat muxt.TemplateName) {
assert.EqualExportedValues(t, muxt.TemplateName{
Method: http.MethodGet,
Host: "",
Path: "/",
Route: "GET /",
Handler: "",
method: http.MethodGet,

Check failure on line 55 in name_test.go

View workflow job for this annotation

GitHub Actions / build

cannot refer to unexported field method in struct literal of type muxt.TemplateName
host: "",

Check failure on line 56 in name_test.go

View workflow job for this annotation

GitHub Actions / build

cannot refer to unexported field host in struct literal of type muxt.TemplateName
path: "/",

Check failure on line 57 in name_test.go

View workflow job for this annotation

GitHub Actions / build

cannot refer to unexported field path in struct literal of type muxt.TemplateName
endpoint: "GET /",

Check failure on line 58 in name_test.go

View workflow job for this annotation

GitHub Actions / build

cannot refer to unexported field endpoint in struct literal of type muxt.TemplateName
handler: "",

Check failure on line 59 in name_test.go

View workflow job for this annotation

GitHub Actions / build

cannot refer to unexported field handler in struct literal of type muxt.TemplateName
}, pat)
},
},
Expand All @@ -66,11 +66,11 @@ func TestNewTemplateName(t *testing.T) {
ExpMatch: true,
TemplateName: func(t *testing.T, pat muxt.TemplateName) {
assert.EqualExportedValues(t, muxt.TemplateName{
Method: http.MethodPost,
Host: "",
Path: "/",
Route: "POST /",
Handler: "",
method: http.MethodPost,
host: "",
path: "/",
endpoint: "POST /",
handler: "",
}, pat)
},
},
Expand All @@ -80,11 +80,11 @@ func TestNewTemplateName(t *testing.T) {
ExpMatch: true,
TemplateName: func(t *testing.T, pat muxt.TemplateName) {
assert.EqualExportedValues(t, muxt.TemplateName{
Method: http.MethodPatch,
Host: "",
Path: "/",
Route: "PATCH /",
Handler: "",
method: http.MethodPatch,
host: "",
path: "/",
endpoint: "PATCH /",
handler: "",
}, pat)
},
},
Expand All @@ -94,11 +94,11 @@ func TestNewTemplateName(t *testing.T) {
ExpMatch: true,
TemplateName: func(t *testing.T, pat muxt.TemplateName) {
assert.EqualExportedValues(t, muxt.TemplateName{
Method: http.MethodDelete,
Host: "",
Path: "/",
Route: "DELETE /",
Handler: "",
method: http.MethodDelete,
host: "",
path: "/",
endpoint: "DELETE /",
handler: "",
}, pat)
},
},
Expand All @@ -108,11 +108,11 @@ func TestNewTemplateName(t *testing.T) {
ExpMatch: true,
TemplateName: func(t *testing.T, pat muxt.TemplateName) {
assert.EqualExportedValues(t, muxt.TemplateName{
Method: http.MethodPut,
Host: "",
Path: "/",
Route: "PUT /",
Handler: "",
method: http.MethodPut,
host: "",
path: "/",
endpoint: "PUT /",
handler: "",
}, pat)
},
},
Expand All @@ -122,11 +122,11 @@ func TestNewTemplateName(t *testing.T) {
ExpMatch: true,
TemplateName: func(t *testing.T, pat muxt.TemplateName) {
assert.EqualExportedValues(t, muxt.TemplateName{
Method: http.MethodPut,
Host: "",
Path: "/ping/pong/{$}",
Route: "PUT /ping/pong/{$}",
Handler: "",
method: http.MethodPut,
host: "",
path: "/ping/pong/{$}",
endpoint: "PUT /ping/pong/{$}",
handler: "",
}, pat)
},
},
Expand Down Expand Up @@ -220,7 +220,7 @@ func TestPattern_parseHandler(t *testing.T) {
t.Run(tt.Name, func(t *testing.T) {
p, err, ok := muxt.NewTemplateName(tt.In)
require.True(t, ok)
require.NotZero(t, p.Handler)
require.NotZero(t, p.handler)
if tt.ExpErr != "" {
assert.ErrorContains(t, err, tt.ExpErr)
} else {
Expand Down

0 comments on commit 86332a6

Please sign in to comment.