Add simple serve

This commit is contained in:
Peter Kaske 2022-05-11 12:35:55 +02:00
parent 8e7d4d2978
commit 30ab451d3a

43
main.go
View File

@ -5,6 +5,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http"
"os" "os"
"os/signal" "os/signal"
"path/filepath" "path/filepath"
@ -27,6 +28,10 @@ type options struct {
Path string Path string
Exclude []string Exclude []string
} }
Serve struct {
Path string
Port int
}
Copy []struct { Copy []struct {
Src string Src string
Dest string Dest string
@ -74,7 +79,6 @@ func main() {
} }
cp(opts) cp(opts)
replace(opts)
if prodParam.Get(tf) { if prodParam.Get(tf) {
opts.ESBuild.MinifyIdentifiers = true opts.ESBuild.MinifyIdentifiers = true
@ -84,11 +88,12 @@ func main() {
} }
api.Build(opts.ESBuild) api.Build(opts.ESBuild)
replace(opts)
}, },
} }
watchFrontend := goyek.Task{ watch := goyek.Task{
Name: "watch-frontend", Name: "watch",
Usage: "", Usage: "",
Params: goyek.Params{cfgPathParam}, Params: goyek.Params{cfgPathParam},
Action: func(tf *goyek.TF) { Action: func(tf *goyek.TF) {
@ -169,13 +174,32 @@ func main() {
} }
}() }()
if opts.Serve.Path != "" {
go func() {
port := 8888
if opts.Serve.Port != 0 {
port = opts.Serve.Port
}
http.Handle("/", http.FileServer(http.Dir(opts.Serve.Path)))
fmt.Printf("Serving contents of %s at :%d\n", opts.Serve.Path, port)
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
if err != nil {
fmt.Printf("%+v\n", err.Error())
os.Exit(1)
}
}()
}
<-c <-c
fmt.Println("\nExit") fmt.Println("\nExit")
os.Exit(0) os.Exit(0)
}, },
} }
flow.DefaultTask = flow.Register(watchFrontend) flow.DefaultTask = flow.Register(watch)
flow.Register(buildOnly) flow.Register(buildOnly)
flow.Main() flow.Main()
} }
@ -221,7 +245,7 @@ func replace(opts options) {
fmt.Printf("Invalid glob pattern: %s\n", op.Pattern) fmt.Printf("Invalid glob pattern: %s\n", op.Pattern)
continue continue
} }
fmt.Printf("Paths: %+v\n", paths)
for _, p := range paths { for _, p := range paths {
if !isFile(p) { if !isFile(p) {
continue continue
@ -238,10 +262,13 @@ func replace(opts options) {
r = os.ExpandEnv(op.Replace) r = os.ExpandEnv(op.Replace)
} }
if strings.Contains(string(read), op.Search) { count := strings.Count(string(read), op.Search)
fmt.Printf("Replacing '%s' with '%s' in %s\n", op.Search, r, p)
newContents := strings.Replace(string(read), op.Search, r, -1) if count > 0 {
fmt.Printf("Replacing %d occurrences of '%s' with '%s' in %s\n", count, op.Search, r, p)
newContents := strings.ReplaceAll(string(read), op.Search, r)
err = ioutil.WriteFile(p, []byte(newContents), 0) err = ioutil.WriteFile(p, []byte(newContents), 0)
if err != nil { if err != nil {
fmt.Printf("%+v\n", err) fmt.Printf("%+v\n", err)
os.Exit(1) os.Exit(1)