You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

110 lines
2.7 KiB

// +build linux darwin
package main
import (
"fmt"
"net/http"
"os"
"strconv"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
var sess *session.Session
var err error
var svc *dynamodb.DynamoDB
func indexHandler(c echo.Context) error {
return c.File("html/home.html")
}
func healthCheckHandler(c echo.Context) error {
return c.JSON(http.StatusOK, `{"alive": true}`)
}
func overallHandler(c echo.Context) error {
devices, _ := GetDevices(svc)
var result []Item
for _, i := range devices.Items {
device := Device{}
err := dynamodbattribute.UnmarshalMap(i, &device)
if err != nil {
return err
}
data, _ := device.History(svc, 1)
one := data[0]
one.Group = device.Group
one.Info.Name = device.Name
one.Info.Model = device.Model
result = append(result, one)
}
return c.JSON(http.StatusOK, result)
}
// func oneDeviceHandler(w http.ResponseWriter, r *http.Request) {
func oneDeviceHandler(c echo.Context) error {
id := c.Param("id")
// default limit is 5
limit, _ := strconv.ParseInt(c.QueryParam("limit"), 10, 64)
if limit == 0 {
limit = 5
}
device, err := GetDevice(svc, id)
if err != nil {
return c.String(http.StatusInternalServerError, "Error unmarshalling")
}
result, err := GetHistory(svc, id, limit)
var ev []Item
if err != nil {
return c.String(http.StatusInternalServerError, "Error unmarshalling")
}
for _, i := range result.Items {
item := Item{}
err = dynamodbattribute.UnmarshalMap(i, &item)
item.Info.Name = device.Name
item.Info.Model = device.Model
if err != nil {
return c.String(http.StatusInternalServerError, "Error unmarshalling")
}
ev = append(ev, item)
}
return c.JSON(http.StatusOK, ev)
}
func main() {
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err = session.NewSession(&aws.Config{
Region: aws.String("ap-southeast-1")},
)
if err != nil {
fmt.Println("aws error ")
fmt.Println(err.Error())
os.Exit(1)
}
// Create DynamoDB client
svc = dynamodb.New(sess)
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "OPTIONS"},
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
}))
e.GET("/health", healthCheckHandler)
e.GET("/id/:id", oneDeviceHandler)
e.GET("/all", overallHandler)
e.GET("/", indexHandler)
e.Logger.Fatal(e.Start(":31101"))
}