Skip to content

Commit

Permalink
fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Nelwhix committed Jun 7, 2023
1 parent 6a74ee0 commit 72c7c35
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 7 deletions.
44 changes: 37 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package main

import (
"log"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
Expand All @@ -16,6 +16,7 @@ import (
)

var root *string
var eventCh = make(chan string)

func main() {
flag.Usage = func () {
Expand Down Expand Up @@ -54,7 +55,9 @@ func main() {

func serve(port int64, errChan chan error) {
go startWatcher()
http.HandleFunc("/events", streamEvents)
http.HandleFunc("/", serveFile)

err := http.ListenAndServe(":" + strconv.FormatInt(port, 10), nil)
if err != nil {
errChan <- err
Expand All @@ -74,13 +77,12 @@ func serveFile(w http.ResponseWriter, r *http.Request) {

var fs http.Handler

// TODO: CREATE OUR OWN FILESERVER METHOD
if (*root == ".") {
fs = http.FileServer(http.Dir(wd))
} else {
fs = http.FileServer(http.Dir(*root))
}

fs.ServeHTTP(w, r)
}

Expand All @@ -105,10 +107,9 @@ func startWatcher() {
if !ok {
return
}
fmt.Fprintf(os.Stdout, "event:%s", event)


if event.Has(fsnotify.Write) {
fmt.Fprintf(os.Stdout, "modified file: %s", event.Name)
eventCh <-"reload"
}
case err, ok := <-watcher.Errors:
if !ok {
Expand All @@ -131,4 +132,33 @@ func startWatcher() {
}

<-make(chan struct{})
}
}

func streamEvents(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)

if !ok {
http.Error(w, "SSE not supported", http.StatusInternalServerError)
return
}

w.Header().Add("Content-Type", "text/event-stream")
w.Header().Add("Access-Control-Allow-Origin", "*")

for raw := range eventCh {
event, err := formatSSE(raw)

if err != nil {
fmt.Println(err)
break
}

_, err = fmt.Fprint(w, event)
if err != nil {
fmt.Println(err)
break
}

flusher.Flush()
}
}
28 changes: 28 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package main

import (
"bytes"
"encoding/json"
"fmt"
"strings"
)

func formatSSE(data string) (string, error) {
m := map[string]string {
"data": data,
}

buff := bytes.NewBuffer([]byte{})
encoder := json.NewEncoder(buff)
err := encoder.Encode(m)

if err != nil {
return "", err
}

sb := strings.Builder{}

sb.WriteString(fmt.Sprintf("data: %v\n\n", buff.String()))

return sb.String(), nil
}

0 comments on commit 72c7c35

Please # to comment.