aboutsummaryrefslogtreecommitdiffstats
path: root/serve.go
blob: 820b6ac4cf95ed912e29cba3ac46f5dedf727a52 (plain) (blame)
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
package main

import (
	"context"
	"flag"
	"fmt"
	"net/http"
	"os"

	"git.sr.ht/~eugenetriguba/subcmd"
)

type serveCmd struct {
	dir  string
	port int
}

func (c *serveCmd) Name() string     { return "serve" }
func (c *serveCmd) Synopsis() string { return "serve the site locally" }
func (c *serveCmd) Usage() string {
	return `serve [-h | --help] [-d | --dir <directory>] [-p | --port <port>]

See ssg-serve(1) for details.`
}
func (c *serveCmd) SetFlags(f *flag.FlagSet) {
	f.StringVar(&c.dir, "d", "dist", "directory to serve")
	f.StringVar(&c.dir, "dir", "dist", "directory to serve")
	f.IntVar(&c.port, "p", 8080, "port to serve on")
	f.IntVar(&c.port, "port", 8080, "port to serve on")
}
func (c *serveCmd) Execute(ctx context.Context, f *flag.FlagSet, args ...any) subcmd.ExitStatus {
	fmt.Fprintf(os.Stderr, "Serving %s at http://localhost:%d\n", c.dir, c.port)
	if err := http.ListenAndServe(fmt.Sprintf(":%d", c.port), http.FileServer(http.Dir(c.dir))); err != nil {
		fatal("%v", err)
	}
	return subcmd.ExitSuccess
}