summaryrefslogtreecommitdiff
path: root/cmd/serve.go
blob: d53e63212cb8811f582f94f28b19f209b2472b66 (plain)
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
package cmd

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"github.com/HimanshuSardana/kite/pkg/config"
)

func runServe(args []string) {
	themeName := DefaultTheme
	port := DefaultPort

	if cfg, err := config.Load("config.yaml"); err == nil && cfg.DefaultTheme != "" {
		themeName = cfg.DefaultTheme
	}

	for i := 2; i < len(args); i++ {
		if args[i] == "--port" && i+1 < len(args) {
			port = args[i+1]
		}
		if args[i] != "--port" && args[i] != "--help" && args[i] != "-h" {
			themeName = args[i]
		}
	}

	themeCSS := fmt.Sprintf("./themes/%s/style.css", themeName)
	outputCSS := "./output/style.css"

	if err := copyFile(themeCSS, outputCSS); err != nil {
		log.Printf("Warning: Could not copy theme CSS: %v", err)
	}

	fs := http.FileServer(http.Dir("./output/"))
	http.Handle("/", fs)

	log.Printf("Serving on http://localhost:%s", port)

	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatalf("Server error: %s\n", err)
	}
}

func copyFile(src, dst string) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()

	if err := os.MkdirAll(filepath.Dir(dst), os.ModePerm); err != nil {
		return err
	}

	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	_, err = io.Copy(out, in)
	return err
}