Skip to content

Commit 086b5b2

Browse files
authored
Fix greedy regex causing time.Time (#123)
The code in question is this small two lines. if (/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)/.test(val)) return "time.Time"; But what happens if the string in the object contains a timestamp and a bunch of other junk meaning it isn't a time at all, but rather just a string. There's a lot of valid use cases for this. For example, parsing syslog...or something. let val = "2023-11-03T02:18:10+00:00 my name is bob" if (/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)/.test(val)) { console.log("time.Time"); } > time.Time Oh no. It also seems to function in this way when the extra junk is on the other side of the timestamp. let val = "my name is bob 2023-11-03T02:18:10+00:00" if (/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)/.test(val)) { console.log("time.Time"); } > time.Time That's no fun. This is easy to overlook, and luckily it's a simple fix. let val = "2023-11-03T02:18:10+00:00 my name is bob" if (/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)$/.test(val)) { console.log("time.Time"); } else { console.log("Fixed") } > Fixed
1 parent e9233d6 commit 086b5b2

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

json-to-go.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ function jsonToGo(json, typename, flatten = true, example = false, allOmitempty
321321
switch (typeof val)
322322
{
323323
case "string":
324-
if (/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)/.test(val))
324+
if (/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(\+\d\d:\d\d|Z)$/.test(val))
325325
return "time.Time";
326326
else
327327
return "string";

0 commit comments

Comments
 (0)