package k8s_manager import ( "github.com/gin-gonic/gin" log "github.com/sirupsen/logrus" "github.com/thoas/go-funk" v1 "k8s.io/api/apps/v1" "net/http" "strings" ) type AppViewModel struct { *AppModel Status string } type AppsViewModel struct { Username string Apps []AppViewModel } func statusString(status *v1.DeploymentStatus, err error) string { if err != nil { if strings.Contains(err.Error(), "not found") { return "Stopped" } return err.Error() } else { if status.AvailableReplicas > 0 { return "Running" } else { return "Error" } } } func AppPage(c *gin.Context) { username := c.MustGet("username").(string) appsvm := funk.Map(GetApps(username), func(a AppModel) AppViewModel { return AppViewModel{AppModel: &a} }).([]AppViewModel) for i := range appsvm { a := &appsvm[i] d, e := K.GetDeploymentStatus(a.AppModel.DeploymentName()) a.Status = statusString(d, e) } vm := &AppsViewModel{ Username: username, Apps: appsvm, } c.HTML(http.StatusOK, "app_view.html", vm) } func AppMiddleware(c *gin.Context) { app := &AppModel{} err := c.ShouldBindJSON(&app) if err == nil { username := c.MustGet("username") if app.UserName != username { c.JSON(http.StatusUnauthorized, gin.H{"msg": "user error."}) c.Abort() } c.Set("app", app) } } func CreateUpdateDeleteApp(c *gin.Context) { app := &AppModel{} err := c.BindJSON(app) if err != nil { log.WithError(err).Error("CreateUpdateDeleteApp") c.JSON(http.StatusBadRequest, gin.H{"msg": "Cannot get data."}) } else { username := c.MustGet("username").(string) if username != app.UserName { c.JSON(http.StatusUnauthorized, gin.H{"msg": "user error."}) return } if c.Request.Method == http.MethodPost { err = app.Create() } else if c.Request.Method == http.MethodPut { err = app.Update() } else if c.Request.Method == http.MethodDelete { err = app.Delete() } if err != nil { log.WithError(err).Error("CreateUpdateDeleteApp", c.Request.Method) c.JSON(http.StatusInternalServerError, gin.H{"msg": "DB error."}) } else { c.JSON(http.StatusOK, gin.H{"msg": "ok"}) } } }