Skip to content
Snippets Groups Projects
Select Git revision
  • 35424b7014ce2d2a3fff41a876d3a07fc682357e
  • master default protected
  • ballinvoher protected
  • old-master
4 results

pages.go

Blame
  • Kevin Lyda's avatar
    Kevin Lyda authored
    35424b70
    History
    pages.go 1.52 KiB
    //
    // pages.go
    // Copyright (C) 2017 kevin <kevin@ie.suberic.net>
    //
    // Distributed under terms of the MIT license.
    //
    
    //go:generate go get -u github.com/mjibson/esc
    //go:generate esc -o static.go -pkg pages static templates
    
    package pages
    
    import (
    	"html/template"
    	"log"
    	"net/http"
    
    	"gitlab.com/lyda/gqgmc/devices/geiger"
    )
    
    // Pages where data for pages goes
    type Pages struct {
    	gc    geiger.Counter
    	gcErr error
    }
    
    type indexPage struct {
    	Model   string
    	Version string
    	Serial  string
    	Volts   int16
    	CPM     uint16
    }
    
    // New create new Pages.
    func New(gc geiger.Counter, gcErr error) Pages {
    	return Pages{gc: gc, gcErr: gcErr}
    }
    
    // Register pages.
    func (p Pages) Register() {
    	http.HandleFunc("/", p.indexHandler)
    	http.Handle("/favicon.ico", http.FileServer(Dir(false, "/static/")))
    	http.Handle("/robots.txt", http.FileServer(Dir(false, "/static/")))
    	http.Handle("/humans.txt", http.FileServer(Dir(false, "/static/")))
    }
    
    func (p Pages) indexHandler(w http.ResponseWriter, r *http.Request) {
    	var indexPg indexPage
    
    	if p.gcErr == nil {
    		indexPg.CPM, _ = p.gc.GetCPM()
    		indexPg.Volts, _ = p.gc.Volts()
    		indexPg.Model = p.gc.Model()
    		indexPg.Version = p.gc.Version()
    		indexPg.Serial = p.gc.Serial()
    	} else {
    		indexPg.CPM = 0
    		indexPg.Volts = 0
    		indexPg.Model = "ERROR"
    		indexPg.Version = "ERROR"
    		indexPg.Serial = "ERROR"
    	}
    
    	index, _ := FSString(false, "index.html")
    	t, err := template.New("index.html").Parse(index)
    	if err != nil {
    		log.Printf("Template error: %s\n", err)
    		return // TODO: 404
    	}
    	t.Execute(w, &indexPg)
    }