1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
|
package main
import (
"embed"
"encoding/json"
"html/template"
"log"
"net/http"
"sort"
"strings"
"github.com/alecthomas/kong"
konghcl "github.com/alecthomas/kong-hcl"
"github.com/gorilla/csrf"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/alecthomas/chroma"
"github.com/alecthomas/chroma/formatters/html"
"github.com/alecthomas/chroma/lexers"
"github.com/alecthomas/chroma/styles"
)
var (
version = "devel"
//go:embed templates/index.html.tmpl
indexTemplate string
//go:embed static
staticFiles embed.FS
htmlTemplate = template.Must(template.New("html").Parse(indexTemplate))
)
type context struct {
Background template.CSS
SelectedLanguage string
Languages []string
SelectedStyle string
Styles []string
CSRFField template.HTML
Version string
}
func index(w http.ResponseWriter, r *http.Request) {
ctx := newContext(r)
err := htmlTemplate.Execute(w, &ctx)
if err != nil {
panic(err)
}
}
type renderRequest struct {
Language string `json:"language"`
Style string `json:"style"`
Text string `json:"text"`
Classes bool `json:"classes"`
}
type renderResponse struct {
Error string `json:"error,omitempty"`
HTML string `json:"html,omitempty"`
Language string `json:"language,omitempty"`
Background string `json:"background,omitempty"`
}
func renderHandler(w http.ResponseWriter, r *http.Request) {
req := &renderRequest{}
err := json.NewDecoder(r.Body).Decode(&req)
var rep *renderResponse
if err != nil {
rep = &renderResponse{Error: err.Error()}
} else {
rep, err = render(req)
if err != nil {
rep = &renderResponse{Error: err.Error()}
}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(rep)
}
func render(req *renderRequest) (*renderResponse, error) {
language := lexers.Get(req.Language)
if language == nil {
language = lexers.Analyse(req.Text)
if language != nil {
req.Language = language.Config().Name
}
}
if language == nil {
language = lexers.Fallback
}
tokens, err := chroma.Coalesce(language).Tokenise(nil, req.Text)
if err != nil {
return nil, err
}
style := styles.Get(req.Style)
if style == nil {
style = styles.Fallback
}
buf := &strings.Builder{}
options := []html.Option{}
if req.Classes {
options = append(options, html.WithClasses(true), html.Standalone(true))
}
formatter := html.New(options...)
err = formatter.Format(buf, style, tokens)
if err != nil {
return nil, err
}
lang := language.Config().Name
if language == lexers.Fallback {
lang = ""
}
return &renderResponse{
Language: lang,
HTML: buf.String(),
Background: html.StyleEntryToCSS(style.Get(chroma.Background)),
}, nil
}
func newContext(r *http.Request) context {
ctx := context{
SelectedStyle: "monokailight",
CSRFField: csrf.TemplateField(r),
Version: version,
}
style := styles.Get(ctx.SelectedStyle)
if style == nil {
style = styles.Fallback
}
ctx.Background = template.CSS(html.StyleEntryToCSS(style.Get(chroma.Background)))
if ctx.SelectedStyle == "" {
ctx.SelectedStyle = "monokailight"
}
for _, lexer := range lexers.Registry.Lexers {
ctx.Languages = append(ctx.Languages, lexer.Config().Name)
}
sort.Strings(ctx.Languages)
for _, style := range styles.Registry {
ctx.Styles = append(ctx.Styles, style.Name)
}
sort.Strings(ctx.Styles)
return ctx
}
func main() {
var cli struct {
Version kong.VersionFlag `help:"Show version."`
Config kong.ConfigFlag `help:"Load configuration." placeholder:"FILE"`
Bind string `help:"HTTP bind address." default:"127.0.0.1:8080"`
CSRFKey string `help:"CSRF key." default:""`
}
ctx := kong.Parse(&cli, kong.Configuration(konghcl.Loader), kong.Vars{"version": version})
log.Printf("Starting chromad %s on http://%s\n", version, cli.Bind)
router := mux.NewRouter()
router.Handle("/", http.HandlerFunc(index)).Methods("GET")
router.Handle("/api/render", http.HandlerFunc(renderHandler)).Methods("POST")
router.Handle("/static/{file:.*}", http.FileServer(http.FS(staticFiles))).Methods("GET")
options := []csrf.Option{}
if cli.CSRFKey == "" {
options = append(options, csrf.Secure(false))
}
root := handlers.CORS()(csrf.Protect([]byte(cli.CSRFKey), options...)(router))
err := http.ListenAndServe(cli.Bind, root)
ctx.FatalIfErrorf(err)
}
|