54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
|
package httpserver
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"database/sql"
|
||
|
"errors"
|
||
|
"net/http"
|
||
|
|
||
|
echo "github.com/labstack/echo/v4"
|
||
|
"github.com/sirupsen/logrus"
|
||
|
|
||
|
"git.janky.solutions/finn/lockserver/config"
|
||
|
"git.janky.solutions/finn/lockserver/openapi"
|
||
|
"git.janky.solutions/finn/lockserver/zwavejs"
|
||
|
)
|
||
|
|
||
|
var server *echo.Echo
|
||
|
|
||
|
type lockserver struct {
|
||
|
ZWaveJS *zwavejs.Client
|
||
|
}
|
||
|
|
||
|
func ListenAndServe(client *zwavejs.Client) {
|
||
|
server = echo.New()
|
||
|
server.HideBanner = true
|
||
|
server.HidePort = true
|
||
|
server.HTTPErrorHandler = handleError
|
||
|
|
||
|
openapi.RegisterHandlersWithBaseURL(server, lockserver{ZWaveJS: client}, "/api")
|
||
|
|
||
|
err := server.Start(config.C.HTTPBind)
|
||
|
if err != http.ErrServerClosed {
|
||
|
logrus.WithError(err).Fatal("error starting http server")
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func handleError(err error, c echo.Context) {
|
||
|
if errors.Is(err, sql.ErrNoRows) {
|
||
|
_ = c.JSON(http.StatusNotFound, map[string]string{"error": "not found"})
|
||
|
return
|
||
|
}
|
||
|
|
||
|
logrus.WithError(err).Error("error handling request")
|
||
|
_ = c.JSON(http.StatusInternalServerError, map[string]string{"error": "internal server error"})
|
||
|
}
|
||
|
|
||
|
func Shutdown(ctx context.Context) error {
|
||
|
if server == nil {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
return server.Shutdown(ctx)
|
||
|
}
|