Skip to content

Commit c87a913

Browse files
committed
Refactor HTML response parsing logic to handle nested elements
1 parent ba69896 commit c87a913

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

response/error.go

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -185,33 +185,40 @@ func parseHTMLResponse(bodyBytes []byte, apiError *APIError, log logger.Logger,
185185
parse = func(n *html.Node) {
186186
if n.Type == html.ElementNode && n.Data == "p" {
187187
var pContent strings.Builder
188-
for c := n.FirstChild; c != nil; c = c.NextSibling {
188+
// Define a function to traverse child nodes of the <p> tag.
189+
var traverseChildren func(*html.Node)
190+
traverseChildren = func(c *html.Node) {
189191
if c.Type == html.TextNode {
190192
// Append text content directly.
191193
pContent.WriteString(strings.TrimSpace(c.Data) + " ")
192194
} else if c.Type == html.ElementNode && c.Data == "a" {
193195
// Extract href attribute value for links.
194-
var href string
195196
for _, attr := range c.Attr {
196197
if attr.Key == "href" {
197-
href = attr.Val
198+
// Append the link to the pContent builder.
199+
pContent.WriteString("[Link: " + attr.Val + "] ")
198200
break
199201
}
200202
}
201-
if href != "" {
202-
// Append the link to the pContent builder.
203-
pContent.WriteString(fmt.Sprintf("[Link: %s] ", href))
204-
}
205203
}
204+
// Recursively traverse all children of the current node.
205+
for child := c.FirstChild; child != nil; child = child.NextSibling {
206+
traverseChildren(child)
207+
}
208+
}
209+
// Start traversing child nodes of the current <p> tag.
210+
for child := n.FirstChild; child != nil; child = child.NextSibling {
211+
traverseChildren(child)
206212
}
207213
finalContent := strings.TrimSpace(pContent.String())
208214
if finalContent != "" {
209215
// Add the content of the <p> tag to messages.
210216
messages = append(messages, finalContent)
211217
}
212218
}
219+
// Continue traversing the document.
213220
for c := n.FirstChild; c != nil; c = c.NextSibling {
214-
parse(c) // Continue traversing the document.
221+
parse(c)
215222
}
216223
}
217224

0 commit comments

Comments
 (0)