Help us shape the future of Go! Take the 2026 Go Developer Survey

text

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 23, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

README

Text Processing

Text processing utilities including code block extraction and format conversion.

Features

  • Extract markdown code blocks (```lang ... ```)
  • Auto-detect language when not specified
  • Parse JSON/YAML with fault-tolerant parser
  • Fallback to text type when no pattern detected
  • Support 15+ languages: Go, Python, JavaScript, TypeScript, Rust, Java, C#, C/C++, Ruby, PHP, Shell, SQL, HTML, CSS, Markdown, etc.
  • Markdown to HTML conversion (GitHub Flavored Markdown support)
  • HTML to Markdown conversion

Go Usage

import "github.com/yaoapp/gou/text"

// Extract all code blocks
blocks := text.Extract(llmResponse)
// Returns: []CodeBlock{{Type: "json", Content: "...", Data: {...}}, ...}

// Extract first block
block := text.ExtractFirst(llmResponse)

// Extract JSON/YAML data directly
data := text.ExtractJSON(llmResponse)

// Extract by type
sqlBlocks := text.ExtractByType(llmResponse, "sql")

// Markdown to HTML
html, err := text.MarkdownToHTML("# Hello\n\nThis is **bold** text.")
// Returns: "<h1 id="hello">Hello</h1>\n<p>This is <strong>bold</strong> text.</p>\n"

// HTML to Markdown
md, err := text.HTMLToMarkdown("<h1>Hello</h1><p>This is <strong>bold</strong> text.</p>")
// Returns: "# Hello\n\nThis is **bold** text."

JavaScript Usage (Yao Process)

// Extract all code blocks
const blocks = Process("text.Extract", llmResponse);
// Returns: [{type: "json", content: "...", data: {...}}, ...]

// Extract first block
const block = Process("text.ExtractFirst", llmResponse);

// Extract JSON/YAML data directly (most common)
const data = Process("text.ExtractJSON", llmResponse);
// Works with: ```json {...} ```, ```yaml ... ```, or raw JSON/YAML

// Extract by type
const sqlBlocks = Process("text.ExtractByType", llmResponse, "sql");

// Markdown to HTML (supports GFM: tables, strikethrough, task lists)
const html = Process("text.MarkdownToHTML", "# Hello\n\nThis is **bold** text.");
// Returns: "<h1 id="hello">Hello</h1>\n<p>This is <strong>bold</strong> text.</p>\n"

// HTML to Markdown
const md = Process("text.HTMLToMarkdown", "<h1>Hello</h1><p>This is <strong>bold</strong> text.</p>");
// Returns: "# Hello\n\nThis is **bold** text."

Supported Types

Category Types
Data json, yaml, xml, html, sql, css, markdown
Languages go, python, javascript, typescript, rust, java, csharp, c, cpp, ruby, php, shell
Fallback text (when no pattern detected)

CodeBlock Structure

interface CodeBlock {
  type: string; // "json", "python", "sql", "text", etc.
  content: string; // Raw content
  data?: any; // Parsed data (JSON/YAML only)
  start?: number; // Start position
  end?: number; // End position
}

Examples

// LLM returns markdown-wrapped JSON
const response = `Here is the result:
\`\`\`json
{"keywords": ["apple", "banana"]}
\`\`\``;

const data = Process("text.ExtractJSON", response);
// Returns: {keywords: ["apple", "banana"]}

// LLM returns raw JSON (also works)
const data2 = Process("text.ExtractJSON", '{"name": "test"}');
// Returns: {name: "test"}

// LLM returns YAML (also works)
const data3 = Process("text.ExtractJSON", "name: test\nvalue: 123");
// Returns: {name: "test", value: 123}

// Plain text fallback
const blocks = Process("text.Extract", "Hello, how are you?");
// Returns: [{type: "text", content: "Hello, how are you?"}]

Markdown/HTML Conversion

Markdown to HTML

Supports GitHub Flavored Markdown (GFM) including:

  • Tables
  • Strikethrough (~~text~~)
  • Task lists (- [x] done)
  • Autolinks
// Basic conversion
const html = Process("text.MarkdownToHTML", "# Title\n\nParagraph with **bold**.");

// GFM table
const tableHtml = Process("text.MarkdownToHTML", `
| Name | Age |
|------|-----|
| John | 30  |
`);

// GFM task list
const taskHtml = Process("text.MarkdownToHTML", `
- [x] Task done
- [ ] Task pending
`);
HTML to Markdown

Converts HTML back to clean Markdown:

// Basic conversion
const md = Process("text.HTMLToMarkdown", "<h1>Title</h1><p>Text</p>");
// Returns: "# Title\n\nText"

// Links and images
const md2 = Process("text.HTMLToMarkdown", '<a href="https://example.com">Link</a>');
// Returns: "[Link](https://example.com)"

// Lists
const md3 = Process("text.HTMLToMarkdown", "<ul><li>Item 1</li><li>Item 2</li></ul>");
// Returns: "- Item 1\n- Item 2"

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractJSON

func ExtractJSON(text string) interface{}

ExtractJSON extracts the first JSON or YAML block and returns parsed data Supports both JSON and YAML as they are both structured data formats Returns nil if no valid JSON/YAML found

func HTMLToMarkdown

func HTMLToMarkdown(htmlContent string) (string, error)

HTMLToMarkdown converts HTML to Markdown Uses goquery-based parsing for reliable HTML handling

func MarkdownToHTML

func MarkdownToHTML(markdown string) (string, error)

MarkdownToHTML converts Markdown text to HTML Supports GitHub Flavored Markdown (GFM) extensions including: - Tables - Strikethrough - Task lists - Autolinks

func ProcessExtract

func ProcessExtract(process *process.Process) interface{}

ProcessExtract text.Extract Extracts code blocks from text (typically LLM output) Handles markdown code blocks and direct JSON/HTML/Code detection

Args:

  • text string - The text to extract code blocks from

Returns: []CodeBlock - Array of extracted code blocks

Usage:

// Extract all code blocks from LLM response
var blocks = Process("text.Extract", llmResponse)
// Returns: [{"type": "json", "content": "{...}", "data": {...}}, ...]

// Handle markdown wrapped JSON
var blocks = Process("text.Extract", "```json\n{\"key\": \"value\"}\n```")
// Returns: [{"type": "json", "content": "{\"key\": \"value\"}", "data": {"key": "value"}}]

func ProcessExtractByType

func ProcessExtractByType(process *process.Process) interface{}

ProcessExtractByType text.ExtractByType Extracts all blocks of a specific type

Args:

  • text string - The text to extract from
  • blockType string - The type to filter by (e.g., "json", "html", "sql")

Returns: []CodeBlock - Array of matching code blocks

Usage:

// Extract only SQL blocks
var sqlBlocks = Process("text.ExtractByType", llmResponse, "sql")

func ProcessExtractFirst

func ProcessExtractFirst(process *process.Process) interface{}

ProcessExtractFirst text.ExtractFirst Extracts and returns only the first code block Useful when you expect only one block (common in LLM responses)

Args:

  • text string - The text to extract from

Returns: CodeBlock or null - The first extracted code block

Usage:

var block = Process("text.ExtractFirst", llmResponse)
if (block != null && block.data != null) {
    // Use block.data directly
}

func ProcessExtractJSON

func ProcessExtractJSON(process *process.Process) interface{}

ProcessExtractJSON text.ExtractJSON Extracts the first JSON or YAML block and returns parsed data directly Most convenient for LLM responses that return structured data Supports both JSON and YAML formats

Args:

  • text string - The text containing JSON or YAML

Returns: parsed data or null

Usage:

// Direct JSON parsing from LLM response
var data = Process("text.ExtractJSON", "```json\n{\"keywords\": [\"a\", \"b\"]}\n```")
// Returns: {"keywords": ["a", "b"]}

// Also works without markdown wrapper
var data = Process("text.ExtractJSON", "{\"keywords\": [\"a\", \"b\"]}")
// Returns: {"keywords": ["a", "b"]}

// YAML is also supported
var data = Process("text.ExtractJSON", "```yaml\nkeywords:\n  - a\n  - b\n```")
// Returns: {"keywords": ["a", "b"]}

func ProcessHTMLToMarkdown

func ProcessHTMLToMarkdown(process *process.Process) interface{}

ProcessHTMLToMarkdown text.HTMLToMarkdown Converts HTML to Markdown Uses goquery-based parsing for reliable HTML handling

Args:

  • html string - The HTML content to convert

Returns: string - The converted Markdown text

Usage:

var md = Process("text.HTMLToMarkdown", "<h1>Hello</h1><p>This is <strong>bold</strong> text.</p>")
// Returns: "# Hello\n\nThis is **bold** text."

// With links and images
var md = Process("text.HTMLToMarkdown", "<a href=\"https://example.com\">Link</a>")
// Returns: "[Link](https://example.com)"

func ProcessMarkdownToHTML

func ProcessMarkdownToHTML(process *process.Process) interface{}

ProcessMarkdownToHTML text.MarkdownToHTML Converts Markdown text to HTML Supports GitHub Flavored Markdown (GFM) extensions including: - Tables, Strikethrough, Task lists, Autolinks

Args:

  • markdown string - The Markdown text to convert

Returns: string - The converted HTML content

Usage:

var html = Process("text.MarkdownToHTML", "# Hello\n\nThis is **bold** text.")
// Returns: "<h1 id=\"hello\">Hello</h1>\n<p>This is <strong>bold</strong> text.</p>\n"

// With GFM table
var html = Process("text.MarkdownToHTML", "| A | B |\n|---|---|\n| 1 | 2 |")
// Returns: "<table>...</table>"

Types

type CodeBlock

type CodeBlock struct {
	Type    string      `json:"type"`            // Language type: json, html, python, sql, etc.
	Content string      `json:"content"`         // Raw content of the code block
	Data    interface{} `json:"data,omitempty"`  // Parsed data (for JSON/YAML)
	Start   int         `json:"start,omitempty"` // Start position in original text
	End     int         `json:"end,omitempty"`   // End position in original text
}

CodeBlock represents an extracted code block from text

func Extract

func Extract(text string) []CodeBlock

Extract extracts code blocks from text (typically LLM output) It handles: 1. Markdown code blocks (```lang ... ```) 2. Direct JSON/HTML/Code without markdown wrapper 3. JSON is parsed using fault-tolerant parser 4. Fallback: returns original text as type "text" if no blocks detected

Returns a slice of CodeBlock with type, content, and parsed data (for JSON)

func ExtractByType

func ExtractByType(text string, blockType string) []CodeBlock

ExtractByType extracts all blocks of a specific type

func ExtractFirst

func ExtractFirst(text string) *CodeBlock

ExtractFirst extracts and returns only the first code block Useful when you expect only one block (common in LLM responses)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL