This commit is contained in:
2025-10-13 13:41:34 +02:00
parent 90f10143da
commit 4b62a9a64b
23 changed files with 679 additions and 196 deletions

View File

@@ -2,10 +2,12 @@ package handler
import (
"crypto/rand"
"io"
"net/http"
"strings"
"github.com/a-h/templ"
"github.com/alecthomas/chroma/v2"
"github.com/alecthomas/chroma/v2/formatters/html"
"github.com/alecthomas/chroma/v2/lexers"
"github.com/alecthomas/chroma/v2/styles"
@@ -13,9 +15,10 @@ import (
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
// generateId generates a random 10-character alphanumeric string.
func generateId() (string, error) {
bytes := make([]byte, 10)
if _, err := rand.Read(bytes); err != nil {
if _, err := io.ReadFull(rand.Reader, bytes); err != nil {
return "", err
}
@@ -25,20 +28,28 @@ func generateId() (string, error) {
return string(bytes), nil
}
// highlight highlights the given content using the specified file extension and theme.
func highlight(content, ext, theme string) (string, error) {
lexer := lexers.Get(ext)
if lexer == nil {
lexer = lexers.Analyse(content)
if lexer == nil {
lexer = lexers.Fallback
var lexer chroma.Lexer
if ext != "" {
lexer = lexers.Get(ext)
if lexer != nil && lexer.Config().Name == "plaintext" {
analysedLexer := lexers.Analyse(content)
if analysedLexer != nil {
lexer = analysedLexer
}
}
}
if lexer == nil {
lexer = lexers.Fallback
}
lexer = chroma.Coalesce(lexer)
formatter := html.New(
html.WithLineNumbers(false),
html.Standalone(false),
html.TabWidth(4),
html.WithLineNumbers(true),
html.TabWidth(4),
)
style := styles.Get(theme)
@@ -52,16 +63,15 @@ func highlight(content, ext, theme string) (string, error) {
}
var buf strings.Builder
err = formatter.Format(&buf, style, iterator)
if err != nil {
if err := formatter.Format(&buf, style, iterator); err != nil {
return "", err
}
return buf.String(), nil
}
// render renders the given component to the response writer, handling any errors.
func render(component templ.Component, w http.ResponseWriter, r *http.Request) {
err := component.Render(r.Context(), w)
if err != nil {
if err := component.Render(r.Context(), w); err != nil {
internal("could not render template", err, w, r)
}
}