package pages import ( "bufio" "bytes" "context" "html/template" htmlfmt "github.com/alecthomas/chroma/v2/formatters/html" "github.com/alecthomas/chroma/v2/lexers" "github.com/alecthomas/chroma/v2/styles" "github.com/carlmjohnson/requests" "github.com/gofiber/fiber/v2" ) // FileView is the file view page func FileView(c *fiber.Ctx) error { var file string url := "https://raw.githubusercontent.com/" + c.Params("user") + "/" + c.Params("repo") + "/" + c.Params("branch") + "/" + c.Params("file") err := requests. URL(url). ToString(&file). Fetch(context.Background()) if err != nil { return c.Status(404).Render("error", fiber.Map{ "error": err, }) } lexer := lexers.Match(c.Params("file")) if lexer == nil { lexer = lexers.Fallback } formatter := htmlfmt.New( htmlfmt.WithClasses(true), htmlfmt.WithLineNumbers(true), htmlfmt.PreventSurroundingPre(false), ) buf := bytes.Buffer{} writer := bufio.NewWriter(&buf) style := styles.Get("native") tokens, err := lexer.Tokenise(nil, file) if err != nil { return c.Status(500).Render("error", fiber.Map{ "error": err, }) } formatter.Format(writer, style, tokens) cssbuf := bytes.Buffer{} cssw := bufio.NewWriter(&cssbuf) formatter.WriteCSS(cssw, style) writer.Flush() cssw.Flush() return c.Render("file", fiber.Map{ "file": template.HTML(buf.String()), "css": template.CSS(cssbuf.String()), "fullname": c.Params("user") + "/" + c.Params("repo"), "name": c.Params("file"), "branch": c.Params("branch"), }) }