Skip to content

Commit

Permalink
Fixing router
Browse files Browse the repository at this point in the history
  • Loading branch information
sudermanjr committed Feb 19, 2023
1 parent 024774a commit 04b97a1
Show file tree
Hide file tree
Showing 6 changed files with 150 additions and 49 deletions.
24 changes: 19 additions & 5 deletions cmd/demo.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package cmd

import (
"fmt"
"os"

"github.com/spf13/cobra"

"github.com/sudermanjr/led-controller/pkg/screen"
Expand All @@ -15,29 +18,40 @@ var (

func init() {
rootCmd.AddCommand(demoCmd)
rootCmd.AddCommand(screenDemoCmd)

demoCmd.Flags().IntVar(&demoDelay, "delay", 100, "The delay in ms of the demo program.")
demoCmd.Flags().IntVar(&demoCount, "count", 1, "The number of loops to run the demo.")
demoCmd.Flags().IntVar(&demoBrightness, "brightness", 150, "The brightness to run the demo at. Must be between min and max.")
demoCmd.Flags().IntVar(&demoGradientLength, "gradient-count", 2048, "The number of steps in the gradient.")

demoCmd.AddCommand(screenDemoCmd)
demoCmd.AddCommand(ledDemoCmd)
}

var demoCmd = &cobra.Command{
Use: "demo",
Short: "Run a demo.",
Long: `Runs a demo.`,
Short: "Commands for running demos.",
Long: `Commands for running demos.`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 1 {
fmt.Println("You must pass a sub-command. Run with --help for help.")
os.Exit(1)
}
},
}

var ledDemoCmd = &cobra.Command{
Use: "led",
Short: "Run a demo of the LED array",
Run: func(cmd *cobra.Command, args []string) {
defer app.Array.WS.Fini()

app.Array.Brightness = demoBrightness
app.Array.Demo(demoCount, demoDelay, demoGradientLength)
},
}

var screenDemoCmd = &cobra.Command{
Use: "screen-demo",
Use: "screen",
Short: "Run a demo of the lcd screen.",
Long: `Runs a demo of the lcd screen.`,
Run: func(cmd *cobra.Command, args []string) {
Expand Down
5 changes: 4 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ require (
go.uber.org/zap v1.24.0
)

require github.com/go-chi/chi/v5 v5.0.8
require (
github.com/go-chi/chi v1.5.4
github.com/go-chi/chi/v5 v5.0.8
)

require (
github.com/agl/ed25519 v0.0.0-20170116200512-5312a6153412 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/go-chi/chi v1.5.4 h1:QHdzF2szwjqVV4wmByUnTcsbIg7UGaQ0tPF2t5GcAIs=
github.com/go-chi/chi v1.5.4/go.mod h1:uaf8YgoFazUOkPBG7fxPftUylNumIev9awIWOENIuEg=
github.com/go-chi/chi/v5 v5.0.8 h1:lD+NLqFcAi1ovnVZpsnObHGW4xb4J8lNmoYVfECH1Y0=
github.com/go-chi/chi/v5 v5.0.8/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/gosexy/to v0.0.0-20141221203644-c20e083e3123 h1:6Q7VB4v0aEgIE6BtsbJhEH0KgFE0f+FHAxXePQp9Klc=
Expand Down
27 changes: 11 additions & 16 deletions pkg/dashboard/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strconv"
"text/template"

"github.com/go-chi/chi/middleware"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"

Expand Down Expand Up @@ -82,24 +83,20 @@ func (a *App) writeTemplate(tmpl *template.Template, data string, w http.Respons

// Initialize sets up an instance of App
func (a *App) Initialize() {
router := chi.NewRouter()
a.Router = chi.NewRouter()

//API
router.Get("/health", a.health)
router.Post("/control", a.control)
router.Post("/demo", a.demo)
router.Get("/", a.rootHandler)
a.Router.MethodFunc("GET", "/health", a.health)
a.Router.MethodFunc("POST", "/control", a.control)
a.Router.MethodFunc("POST", "/demo", a.demo)
a.Router.MethodFunc("GET", "/", a.rootHandler)

a.Router.Use(middleware.Recoverer)
a.Router.Use(LoggingMiddleware(a.Logger))

// HTML Dashboard
fileServer := http.FileServer(http.FS(assets))
router.Handle("/static/*", fileServer)
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
a.rootHandler(w, r)
})
a.Router.Handle("/static/*", fileServer)

if a.Screen != nil {
// Display Info On Screen
Expand All @@ -109,9 +106,7 @@ func (a *App) Initialize() {
}
}

a.ButtonPin = 4

a.Router = router
a.ButtonPin = 4 // TODO: this probably should be more dynamic
}

// Run starts the http server
Expand Down
62 changes: 62 additions & 0 deletions pkg/dashboard/logging.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package dashboard

import (
"net/http"
"time"

"go.uber.org/zap"
)

// responseWriter is a minimal wrapper for http.ResponseWriter that allows the
// written HTTP status code to be captured for logging.
type responseWriter struct {
http.ResponseWriter
status int
wroteHeader bool
}

func wrapResponseWriter(w http.ResponseWriter) *responseWriter {
return &responseWriter{ResponseWriter: w}
}

func (rw *responseWriter) Status() int {
return rw.status
}

func (rw *responseWriter) WriteHeader(code int) {
if rw.wroteHeader {
return
}

rw.status = code
rw.ResponseWriter.WriteHeader(code)
rw.wroteHeader = true
}

// LoggingMiddleware logs the incoming HTTP request & its duration.
func LoggingMiddleware(logger *zap.SugaredLogger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
w.WriteHeader(http.StatusInternalServerError)
logger.Errorw("error handling request",
"error", err,
)
}
}()

start := time.Now()
wrapped := wrapResponseWriter(w)
next.ServeHTTP(wrapped, r)
logger.Debugw("handled request",
"status", wrapped.status,
"method", r.Method,
"path", r.URL.EscapedPath(),
"duration", time.Since(start),
)
}

return http.HandlerFunc(fn)
}
}
79 changes: 52 additions & 27 deletions pkg/dashboard/templates/dashboard.gohtml
Original file line number Diff line number Diff line change
@@ -1,41 +1,66 @@
{{define "dashboard"}}

<h1>LED Control</h1>

<div class="container-card">
<div class="card">
<h1 class="card-heading">Control</h1>
<div class="card">
<h1 class="card-heading">Control</h1>

<form action="/control" method="post" id="control">
<label for="control-color">Color</label>
<input id="control-color" type="color" name="color">
<form action="/control" method="post" id="control">
<label for="control-color">Color</label>
<input id="control-color" type="color" name="color" />

<label for="control-brightness">Brightness</label>
<input type="range" min="0" max="100" name="brightness">
<label for="control-brightness">Brightness</label>
<input type="range" min="0" max="100" name="brightness" />

<input type="submit" value="set" id="control-submit">
</form>
</div>
<input type="submit" value="set" id="control-submit" />
</form>
</div>

<div class="card">
<h1 class="card-heading">Demo</h1>
<div class="card">
<h1 class="card-heading">Demo</h1>

<form action="/demo" method="post" id="demo">
<label for="demo-count">Count</label>
<input id="demo-count" type="number" name="count" value="1" min="1" max="10">
<form action="/demo" method="post" id="demo">
<label for="demo-count">Count</label>
<input
id="demo-count"
type="number"
name="count"
value="1"
min="1"
max="10"
/>

<label for="demo-delay">Delay (in ms)</label>
<input id="demo-delay" type="number" name="delay" value="100" min="0" max="10000">
<label for="demo-delay">Delay (in ms)</label>
<input
id="demo-delay"
type="number"
name="delay"
value="100"
min="0"
max="10000"
/>

<label for="demo-brightness">Brightness</label>
<input id="demo-brightness" type="range" min="0" max="100" name="brightness">
<label for="demo-brightness">Brightness</label>
<input
id="demo-brightness"
type="range"
min="0"
max="100"
name="brightness"
/>

<label for="demo-gradient-steps">Gradient Steps</label>
<input id="demo-gradient-steps" type="number" name="gradient-steps" value="2048" min="10" max="10000">
<label for="demo-gradient-steps">Gradient Steps</label>
<input
id="demo-gradient-steps"
type="number"
name="gradient-steps"
value="2048"
min="10"
max="10000"
/>

<input type="submit" value="run" id="demo-submit">
</form>
</div>
<input type="submit" value="run" id="demo-submit" />
</form>
</div>
</div>

{{end}}
{{ end }}

0 comments on commit 04b97a1

Please sign in to comment.