74 lines
1.5 KiB
Go
Executable File
74 lines
1.5 KiB
Go
Executable File
/*
|
|
Serve is a very simple static file server in go
|
|
Usage:
|
|
-p="8100": port to serve on
|
|
-d=".": the directory of static files to host
|
|
Navigating to http://localhost:8100 will display the index.html or directory
|
|
listing file.
|
|
*/
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"io/ioutil"
|
|
"local/args"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func main() {
|
|
fs := args.NewArgSet()
|
|
fs.Append(args.STRING, "p", "port to serve", "8100")
|
|
fs.Append(args.STRING, "d", "static path to serve", "./public")
|
|
if err := fs.Parse(); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
d := fs.Get("d").GetString()
|
|
p := fs.Get("p").GetString()
|
|
go serve(d, p)
|
|
go poll(path.Join(d, "csv"), time.Minute)
|
|
|
|
<-context.Background().Done()
|
|
}
|
|
|
|
func serve(directory, port string) {
|
|
port = strings.TrimPrefix(port, ":")
|
|
http.Handle("/", http.FileServer(http.Dir(directory)))
|
|
log.Printf("Serving %s on HTTP port: %s\n", directory, port)
|
|
log.Fatal(http.ListenAndServe(":"+port, nil))
|
|
}
|
|
|
|
func poll(path string, interval time.Duration) {
|
|
for {
|
|
select {
|
|
case <-context.Background().Done():
|
|
case <-time.After(interval):
|
|
if err := refresh(path); err != nil {
|
|
log.Println(err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func refresh(path string) error {
|
|
url := "https://docs.google.com/spreadsheets/d/14F7zRrwGT6JkCeZqZLPM2r2GScrm9FLFxlPtDINbNWg/gviz/tq?tqx=out:csv"
|
|
resp, err := http.Get(url)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
b, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := ioutil.WriteFile(path, b, os.ModePerm); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|