package main import ( "encoding/json" "fmt" "net/http" "os" "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/flosch/pongo2" "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) var tplHome = pongo2.Must(pongo2.FromFile("html/home.html")) var sess *session.Session var err error var svc *dynamodb.DynamoDB // func indexHandler(w http.ResponseWriter, r *http.Request) { func indexHandler(c echo.Context) error { // Execute the template per HTTP request // err := tplHome.ExecuteWriter(pongo2.Context{"query": "dddd"}, w) out, err := tplHome.Execute(pongo2.Context{"query": "dddd"}) if err != nil { return err } return c.HTML(http.StatusOK, out) } func healthCheckHandler(c echo.Context) error { // func healthCheckHandler(w http.ResponseWriter, r *http.Request) { // A very simple health check. // w.WriteHeader(http.StatusOK) // w.Header().Set("Content-Type", "application/json") // In the future we could report back on the status of our DB, or our cache // (e.g. Redis) by performing a simple PING, and include them in the response. // io.WriteString(w, `{"alive": true}`) 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) result = append(result, data[0]) } // b, _ := json.Marshal(result) return c.JSON(http.StatusOK, result) } // func oneDeviceHandler(w http.ResponseWriter, r *http.Request) { func oneDeviceHandler(c echo.Context) error { id := c.Param("id") result, err := GetHistory(svc, id, 5) var ev []Item if err != nil { // w.WriteHeader(http.StatusInternalServerError) // w.Header().Set("Content-Type", "application/json") // io.WriteString(w, fmt.Sprintf(`{"msg":"%+v"}`, err)) return c.String(http.StatusInternalServerError, "Error unmarshalling") } for _, i := range result.Items { item := Item{} err = dynamodbattribute.UnmarshalMap(i, &item) if err != nil { // w.WriteHeader(http.StatusInternalServerError) // w.Header().Set("Content-Type", "application/json") // io.WriteString(w, fmt.Sprintf(`{"msg":"%+v"}`, err)) return c.String(http.StatusInternalServerError, "Error unmarshalling") } ev = append(ev, item) } // w.WriteHeader(http.StatusOK) // w.Header().Set("Content-Type", "application/json") b, _ := json.Marshal(ev) // io.WriteString(w, string(b)) return c.JSON(http.StatusOK, b) } 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) // func main() { // session, err := r.Connect(r.ConnectOpts{ // Address: "localhost:28015", // Database: "rtcom", // }) // if err != nil { // log.Panic(err.Error()) // } // router := NewRouter() // router.Handle("channel add", addChannel) // router.Handle("channel subscribe", subscribeChannel) // http.Handle("/", router) // http.ListenAndServe(":4000", nil) // r := mux.NewRouter() // // r := http.NewServeMux() // // r.HandleFunc("/", HomeHandler) // // r.HandleFunc("/products", ProductsHandler) // // r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT") // // r.HandleFunc("/authors", handler).Queries("surname", "{surname}") // r.HandleFunc("/health", healthCheckHandler) // r.HandleFunc("/id/{id}", oneDeviceHandler) // r.HandleFunc("/all", overallHandler) // r.HandleFunc("/", indexHandler) // log.Fatal(http.ListenAndServe(":8000", // handlers.CORS( // handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}), // handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"}), // handlers.AllowedOrigins([]string{"*"}), // handlers.IgnoreOptions(), // )(r)), // ) 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(":8000")) }