mirror of
https://github.com/skidoodle/pastebin
synced 2026-04-28 03:07:40 +02:00
small refactor
This commit is contained in:
+22
-53
@@ -2,20 +2,15 @@ package handler
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"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"
|
||||
"time"
|
||||
)
|
||||
|
||||
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
|
||||
// generateId generates a random 10-character alphanumeric string.
|
||||
func generateId() (string, error) {
|
||||
bytes := make([]byte, 10)
|
||||
if _, err := io.ReadFull(rand.Reader, bytes); err != nil {
|
||||
@@ -28,50 +23,24 @@ 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) {
|
||||
var lexer chroma.Lexer
|
||||
func TimeAgo(t time.Time) string {
|
||||
ago := time.Since(t)
|
||||
seconds := int(ago.Seconds())
|
||||
|
||||
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(true),
|
||||
html.TabWidth(4),
|
||||
)
|
||||
|
||||
style := styles.Get(theme)
|
||||
if style == nil {
|
||||
style = styles.Fallback
|
||||
}
|
||||
|
||||
iterator, err := lexer.Tokenise(nil, content)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var buf strings.Builder
|
||||
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) {
|
||||
if err := component.Render(r.Context(), w); err != nil {
|
||||
internal("could not render template", err, w, r)
|
||||
switch {
|
||||
case seconds < 60:
|
||||
return fmt.Sprintf("%ds ago", seconds)
|
||||
case seconds < 3600:
|
||||
return fmt.Sprintf("%dm ago", seconds/60)
|
||||
case seconds < 86400:
|
||||
return fmt.Sprintf("%dh ago", seconds/3600)
|
||||
default:
|
||||
return fmt.Sprintf("%dd ago", seconds/86400)
|
||||
}
|
||||
}
|
||||
|
||||
func hash(content string) string {
|
||||
h := sha256.New()
|
||||
h.Write([]byte(content))
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user