mirror of
https://github.com/shouptech/tempgopher.git
synced 2026-02-03 16:49:42 +00:00
Add web server
This commit is contained in:
parent
3f9fbc5f7c
commit
31ffadd2cf
1 changed files with 49 additions and 4 deletions
53
web.go
53
web.go
|
|
@ -1,13 +1,36 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RunWeb launches a web server
|
// PingHandler responds to get requests with the message "pong".
|
||||||
func RunWeb(sc <-chan State, done <-chan bool, wg *sync.WaitGroup) {
|
func PingHandler(c *gin.Context) {
|
||||||
states := make(map[string]State)
|
c.String(http.StatusOK, "pong")
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetupRouter initializes the gin router.
|
||||||
|
func SetupRouter() *gin.Engine {
|
||||||
|
r := gin.Default()
|
||||||
|
|
||||||
|
gin.SetMode(gin.ReleaseMode)
|
||||||
|
|
||||||
|
// Ping
|
||||||
|
r.GET("/ping", PingHandler)
|
||||||
|
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunWeb launches a web server. sc is used to update the states from the Thermostats.
|
||||||
|
func RunWeb(sc <-chan State, done <-chan bool, wg *sync.WaitGroup) {
|
||||||
|
// Update sensor states when a new state comes back from the thermostat.
|
||||||
|
states := make(map[string]State)
|
||||||
go func() {
|
go func() {
|
||||||
for {
|
for {
|
||||||
s := <-sc
|
s := <-sc
|
||||||
|
|
@ -15,7 +38,29 @@ func RunWeb(sc <-chan State, done <-chan bool, wg *sync.WaitGroup) {
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
<-done
|
// Launch the web server
|
||||||
|
r := SetupRouter()
|
||||||
|
srv := &http.Server{
|
||||||
|
Addr: ":8080",
|
||||||
|
Handler: r,
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
// service connections
|
||||||
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
|
log.Fatalf("listen: %s\n", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Wait for the done signal
|
||||||
|
<-done
|
||||||
|
log.Println("Shutdown Server ...")
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := srv.Shutdown(ctx); err != nil {
|
||||||
|
log.Fatal("Server Shutdown:", err)
|
||||||
|
}
|
||||||
|
log.Println("Server exiting")
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue