105 lines
2.1 KiB
Go
105 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/labstack/echo/v4/middleware"
|
|
"github.com/labstack/gommon/log"
|
|
)
|
|
|
|
const TimeFormat = "2006-01-02 15:04:05"
|
|
|
|
// the condition is: distance >= threshold
|
|
var value uint16 = 0
|
|
var valueMutex sync.Mutex
|
|
|
|
type ReadReq struct {
|
|
token string `body:"token"`
|
|
}
|
|
|
|
type WriteReq struct {
|
|
value uint16 `body:"value"`
|
|
token string `body:"token"`
|
|
}
|
|
|
|
func main() {
|
|
app := echo.New()
|
|
app.Logger.SetLevel(log.INFO)
|
|
|
|
app.Use(middleware.RecoverWithConfig(middleware.RecoverConfig{
|
|
StackSize: 1 << 10,
|
|
LogLevel: log.ERROR,
|
|
}))
|
|
app.Use(middleware.Secure())
|
|
|
|
app.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
|
|
Format: "${time_custom} ${method} ${uri} ---> ${status} in ${latency_human} (${bytes_out} bytes)\n",
|
|
CustomTimeFormat: TimeFormat,
|
|
}))
|
|
app.Use(middleware.RemoveTrailingSlash())
|
|
|
|
app.OnAddRouteHandler = func(host string, route echo.Route, handler echo.HandlerFunc, middleware []echo.MiddlewareFunc) {
|
|
now := time.Now()
|
|
fmt.Printf("%s registered %-6s %s\n", now.Format(TimeFormat), route.Method, route.Path)
|
|
}
|
|
app.HTTPErrorHandler = func(err error, c echo.Context) {
|
|
if c.Response().Committed {
|
|
log.Error(err)
|
|
return
|
|
}
|
|
|
|
code := http.StatusInternalServerError
|
|
var response any = err.Error()
|
|
|
|
var httpErr *echo.HTTPError
|
|
if errors.As(err, &httpErr) {
|
|
code = httpErr.Code
|
|
response = httpErr
|
|
}
|
|
|
|
if code >= 500 {
|
|
log.Error(err)
|
|
}
|
|
|
|
err2 := c.JSON(code, response)
|
|
if err2 != nil {
|
|
log.Error(err2)
|
|
}
|
|
}
|
|
|
|
app.GET("/", func(c echo.Context) error {
|
|
return c.JSON(http.StatusOK, "Hello, World!")
|
|
})
|
|
|
|
app.GET("/read", func(c echo.Context) error {
|
|
var data ReadReq
|
|
err := c.Bind(&data)
|
|
if err != nil {
|
|
return c.NoContent(http.StatusBadRequest)
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, echo.Map{"value": value})
|
|
})
|
|
|
|
app.POST("/write", func(c echo.Context) error {
|
|
var data WriteReq
|
|
err := c.Bind(&data)
|
|
if err != nil {
|
|
return c.NoContent(http.StatusBadRequest)
|
|
}
|
|
|
|
valueMutex.Lock()
|
|
value = data.value
|
|
valueMutex.Unlock()
|
|
|
|
return c.NoContent(http.StatusOK)
|
|
})
|
|
|
|
log.Fatal(app.Start(":1323"))
|
|
}
|