htmgo/htmgo-site/pages/examples/code.go

70 lines
1.6 KiB
Go
Raw Normal View History

2024-10-28 16:39:46 +00:00
package examples
2024-10-28 15:32:50 +00:00
import (
"bytes"
2024-10-28 15:32:50 +00:00
"fmt"
"github.com/maddalax/htmgo/framework/h"
"htmgo-site/ui"
"io"
"log/slog"
"net/http"
2024-10-28 23:47:00 +00:00
"os"
"reflect"
"runtime"
2024-10-28 16:39:46 +00:00
"strings"
"time"
2024-10-28 15:32:50 +00:00
)
func GetGithubPath(path string) string {
2024-10-28 16:39:46 +00:00
path = strings.ReplaceAll(path, "/partials/examples/", "/partials/snippets/")
2024-10-28 15:56:03 +00:00
return fmt.Sprintf("https://github.com/maddalax/htmgo/tree/master/htmgo-site/partials%s.go", path)
2024-10-28 15:32:50 +00:00
}
func GetGithubRawPath(path string) string {
2024-10-28 16:39:46 +00:00
path = strings.ReplaceAll(path, "/examples/", "/snippets/")
return fmt.Sprintf("https://raw.githubusercontent.com/maddalax/htmgo/master/htmgo-site/partials%s.go", path)
}
var RenderCodeToStringCached = h.CachedPerKeyT(time.Minute*30, func(snippet *Snippet) (string, h.GetElementFunc) {
return snippet.path, func() *h.Element {
return renderCodeToString(snippet)
}
})
func renderCodeToString(snippet *Snippet) *h.Element {
2024-10-28 23:47:00 +00:00
source := ""
// in development, use the local file
if h.IsDevelopment() {
ptr := reflect.ValueOf(snippet.partial).Pointer()
fnInfo := runtime.FuncForPC(ptr)
if fnInfo == nil {
return h.Empty()
}
file, _ := fnInfo.FileLine(ptr)
b, err := os.ReadFile(file)
if err != nil {
return h.Empty()
}
source = string(b)
} else {
url := GetGithubRawPath(snippet.path)
slog.Info("getting snippet source code", slog.String("url", url))
resp, err := http.Get(url)
if err != nil {
return h.Empty()
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return h.Empty()
}
out := bytes.NewBuffer(nil)
_, err = io.Copy(out, resp.Body)
if err != nil {
return h.Empty()
}
source = out.String()
}
2024-10-28 23:47:00 +00:00
return ui.CodeSnippet(source, "border-radius: 0.5rem;")
2024-10-28 15:32:50 +00:00
}