func ApplicationConfigFlowWeightPUT()

in pkg/admin/handler/application.go [311:387]


func ApplicationConfigFlowWeightPUT(rt core_runtime.Runtime) gin.HandlerFunc {
	return func(c *gin.Context) {
		var (
			ApplicationName = ""
			body            = struct {
				FlowWeightSets []model.FlowWeightSet `json:"flowWeightSets"`
			}{}
		)
		ApplicationName = c.Query("appName")
		if ApplicationName == "" {
			c.JSON(http.StatusBadRequest, model.NewErrorResp("application name is required"))
		}
		if err := c.Bind(&body); err != nil {
			c.JSON(http.StatusBadRequest, model.NewErrorResp(err.Error()))
			return
		}
		// get from store, or generate default resource
		isNotExist := false
		res, err := service.GetConfigurator(rt, ApplicationName)
		if err != nil {
			if core_store.IsResourceNotFound(err) {
				// for check app exist
				data, err := service.GetApplicationDetail(rt, &model.ApplicationDetailReq{AppName: ApplicationName})
				if err != nil {
					c.JSON(http.StatusNotFound, model.NewErrorResp(err.Error()))
					return
				} else if data == nil {
					c.JSON(http.StatusNotFound, model.NewErrorResp("application not found"))
					return
				}
				res = generateDefaultConfigurator(ApplicationName, consts.ScopeApplication, consts.ConfiguratorVersionV3, true)
				isNotExist = true
			} else {
				c.JSON(http.StatusInternalServerError, model.NewErrorResp(err.Error()))
				return
			}
		}

		// remove old
		res.Spec.RangeConfigsToRemove(func(conf *mesh_proto.OverrideConfig) (IsRemove bool) {
			return isFlowWeight(conf)
		})
		// append new
		for _, set := range body.FlowWeightSets {
			paramMatch := make([]*mesh_proto.ParamMatch, 0, len(set.Scope))
			for _, match := range set.Scope {
				paramMatch = append(paramMatch, &mesh_proto.ParamMatch{
					Key:   *match.Key,
					Value: model.ModelStringMatchToStringMatch(match.Value),
				})
			}
			res.Spec.Configs = append(res.Spec.Configs, &mesh_proto.OverrideConfig{
				Side:       consts.SideProvider,
				Parameters: map[string]string{`weight`: strconv.Itoa(int(set.Weight))},
				Match: &mesh_proto.ConditionMatch{
					Param: paramMatch,
				},
				XGenerateByCp: true,
			})
		}
		// restore
		if isNotExist {
			err = service.CreateConfigurator(rt, ApplicationName, res)
			if err != nil {
				c.JSON(http.StatusInternalServerError, model.NewErrorResp(err.Error()))
				return
			}
		} else {
			err = service.UpdateConfigurator(rt, ApplicationName, res)
			if err != nil {
				c.JSON(http.StatusInternalServerError, model.NewErrorResp(err.Error()))
				return
			}
		}
		c.JSON(http.StatusOK, model.NewSuccessResp(nil))
	}
}