This repository has been archived on 2024-03-03. You can view files and clone it, but cannot push or open issues or pull requests.
minifaas/app.go

80 lines
1.5 KiB
Go
Raw Normal View History

package main
import (
"context"
"io"
"log"
"net/http"
"time"
"github.com/docker/docker/pkg/stdcopy"
"github.com/gin-gonic/gin"
"github.com/nemunaire/minifaas/engine/docker"
2021-05-02 14:04:18 +00:00
"github.com/nemunaire/minifaas/ui"
)
type App struct {
router *gin.Engine
srv *http.Server
}
func NewApp() App {
//gin.SetMode(gin.ReleaseMode)
gin.ForceConsoleColor()
router := gin.Default()
2021-05-02 14:04:18 +00:00
ui.DeclareRoutes(router)
router.GET("/api/version", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"version": 0.1})
})
router.GET("/api/ps", func(c *gin.Context) {
containers, err := docker.Ps()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err})
return
}
c.JSON(http.StatusOK, containers)
})
router.GET("/api/run", func(c *gin.Context) {
stream, err := docker.RunHello()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err})
}
_, err = stdcopy.StdCopy(c.Writer, c.Writer, stream)
if err != nil && err != io.EOF {
c.JSON(http.StatusInternalServerError, gin.H{"error": err})
}
})
app := App{
router: router,
}
return app
}
func (app *App) Start() {
app.srv = &http.Server{
Addr: ":8082",
Handler: app.router,
}
if err := app.srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}
func (app *App) Stop() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := app.srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
}