I need a golang web server that serves markdown files rendered as html and the index.html should be a list of links to the available files.
Assistant
Here's a basic implementation of a Golang web server that serves Markdown files as rendered HTML. It also serves an index.html listing links to the available Markdown files.
To achieve this, we'll need to:
Traverse the directory to list Markdown files.
Convert Markdown files to HTML.
Build an index page with links to these files.
First, install the necessary package for Markdown rendering. We can use the blackfriday package:
code
go get github.com/russross/blackfriday/v2
Now, here's the code for the web server:
go
package main
import (
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"path/filepath"
"strings"
"github.com/russross/blackfriday/v2"
)
// A struct to hold the links to the Markdown files
type Page struct {
Title string
Links []string
}
func main() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/view/", viewHandler)
log.Println("Starting server on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
// Handler to render the index page with links to Markdown files
func indexHandler(w http.ResponseWriter, r *http.Request) {
files, err := ioutil.ReadDir("./markdown")
if err != nil {
http.Error(w, "Could not read markdown directory", http.StatusInternalServerError)
return
}
links := []string{}
for _, file := range files {
if strings.HasSuffix(file.Name(), ".md") {
links.append(file.Name())
}
}
tmpl, err := template.New("index").Parse(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Markdown Files</title>
</head>
<body>
<h1>Markdown Files</h1>
<ul>
{{range .Links}}
<li><a href="/view/{{.}}">{{.}}</a></li>
{{end}}
</ul>
</body>
</html>
`)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
page := Page{
Title: "Markdown Files",
Links: links,
}
err = tmpl.Execute(w, page)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
// Handler to render the Markdown content as HTML
func viewHandler(w http.ResponseWriter, r *http.Request) {
filename := r.URL.Path[len("/view/"):]
if !strings.HasSuffix(filename, ".md") {
http.NotFound(w, r)
return
}
filePath := filepath.Join("markdown", filename)
content, err := ioutil.ReadFile(filePath)
if err != nil {
http.NotFound(w, r)
return
}
output := blackfriday.Run(content)
w.Header().Set("Content-Type", "text/html")
w.Write(output)
}
Place your Markdown files in a directory called markdown in the same directory as your Go application.
Run the Go server using go run main.go.
Open a browser and navigate to http://localhost:8080 to see the list of Markdown files with links. Click on a link to view the rendered HTML of the corresponding Markdown file.
This is a basic implementation and might need adjustments based on your specific requirements. Ensure you handle errors and edge cases (e.g., non-existent files) gracefully in a production environment.