ยง2023-07-07
$ pwd
/opt/xfs/home/alexlai/build/caddy-markdown-test/demo/munetakaJupyterHub
$ go mod init alexlai
$ go get -u github.com/russross/blackfriday/v2
- main.go
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"github.com/russross/blackfriday/v2"
)
func markdownHandler(w http.ResponseWriter, r *http.Request) {
filePath := r.URL.Path[1:] // Remove leading slash
// Check if the requested path is a directory
if fileInfo, err := os.Stat(filePath); err == nil && fileInfo.IsDir() {
filePath = filepath.Join(filePath, "index.md") // Append "index.md" for directory requests
}
// Check if the requested file exists
if _, err := os.Stat(filePath); os.IsNotExist(err) {
http.NotFound(w, r)
return
}
// Read the markdown file
markdownBytes, err := ioutil.ReadFile(filePath)
if err != nil {
http.Error(w, "Failed to read file", http.StatusInternalServerError)
return
}
// Convert markdown to HTML using blackfriday
htmlBytes := blackfriday.Run(markdownBytes)
// Set the content type header to HTML
w.Header().Set("Content-Type", "text/html")
// Write the HTML response
_, _ = w.Write(htmlBytes)
}
func main() {
http.HandleFunc("/", markdownHandler)
port := "8080"
fmt.Printf("Starting server on port %s...\n", port)
err := http.ListenAndServe(":"+port, nil)
if err != nil {
fmt.Printf("Server error: %s\n", err)
}
}
- run
$ go run main.go
Starting server on port 8080...