Files
go-grip/pkg/webserver.go

87 lines
1.7 KiB
Go
Raw Normal View History

2024-10-09 22:03:53 +02:00
package pkg
import (
2024-10-09 22:49:34 +02:00
"bytes"
2024-10-09 22:03:53 +02:00
"fmt"
"log"
"net/http"
2024-10-09 22:49:34 +02:00
"path"
2024-10-09 22:03:53 +02:00
"path/filepath"
2024-10-09 22:49:34 +02:00
"regexp"
2024-10-09 22:03:53 +02:00
"text/template"
)
type htmlStruct struct {
Content string
Darkmode bool
}
2024-10-09 22:49:34 +02:00
func (client *Client) Serve(file string) error {
dir := http.Dir("./")
chttp := http.NewServeMux()
chttp.Handle("/", http.FileServer(dir))
// Regex for markdown
regex := regexp.MustCompile(`(?i)\.md$`)
2024-10-09 22:03:53 +02:00
// Serve website with rendered markdown
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
2024-10-09 22:49:34 +02:00
if regex.MatchString(r.URL.Path) {
// Open file and convert to html
bytes, err := readToString(dir, r.URL.Path)
htmlContent := client.MdToHTML(bytes)
// Serve
err = serveTemplate(w, htmlStruct{Content: string(htmlContent), Darkmode: client.Dark})
if err != nil {
log.Fatal(err)
}
} else {
chttp.ServeHTTP(w, r)
2024-10-09 22:03:53 +02:00
}
})
2024-10-09 22:49:34 +02:00
addr := fmt.Sprintf("http://localhost:%d/", client.Port)
2024-10-09 22:03:53 +02:00
fmt.Printf("Starting server: %s\n", addr)
2024-10-09 22:49:34 +02:00
if file != "" {
addr = path.Join(addr, file)
}
2024-10-09 22:03:53 +02:00
if client.OpenBrowser {
2024-10-09 22:49:34 +02:00
err := Open(addr)
if err != nil {
log.Println("Error:", err)
}
2024-10-09 22:03:53 +02:00
}
2024-10-09 22:49:34 +02:00
err := http.ListenAndServe(fmt.Sprintf(":%d", client.Port), nil)
return err
}
2024-10-09 22:03:53 +02:00
2024-10-09 22:49:34 +02:00
func readToString(dir http.Dir, filename string) ([]byte, error) {
f, err := dir.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
var buf bytes.Buffer
_, err = buf.ReadFrom(f)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
2024-10-09 22:03:53 +02:00
}
func serveTemplate(w http.ResponseWriter, html htmlStruct) error {
w.Header().Set("Content-Type", "text/html")
lp := filepath.Join("templates", "layout.html")
tmpl, err := template.ParseFiles(lp)
if err != nil {
return err
}
err = tmpl.Execute(w, html)
return err
}