当前位置: 首页>>代码示例>>Golang>>正文


Golang simplejson.New函数代码示例

本文整理汇总了Golang中github.com/grafana/grafana/pkg/components/simplejson.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Notify

func (this *PagerdutyNotifier) Notify(evalContext *alerting.EvalContext) error {
	metrics.M_Alerting_Notification_Sent_PagerDuty.Inc(1)

	if evalContext.Rule.State == m.AlertStateOK && !this.AutoResolve {
		this.log.Info("Not sending a trigger to Pagerduty", "state", evalContext.Rule.State, "auto resolve", this.AutoResolve)
		return nil
	}

	eventType := "trigger"
	if evalContext.Rule.State == m.AlertStateOK {
		eventType = "resolve"
	}

	this.log.Info("Notifying Pagerduty", "event_type", eventType)

	bodyJSON := simplejson.New()
	bodyJSON.Set("service_key", this.Key)
	bodyJSON.Set("description", evalContext.Rule.Name+" - "+evalContext.Rule.Message)
	bodyJSON.Set("client", "Grafana")
	bodyJSON.Set("event_type", eventType)
	bodyJSON.Set("incident_key", "alertId-"+strconv.FormatInt(evalContext.Rule.Id, 10))

	ruleUrl, err := evalContext.GetRuleUrl()
	if err != nil {
		this.log.Error("Failed get rule link", "error", err)
		return err
	}
	bodyJSON.Set("client_url", ruleUrl)

	if evalContext.ImagePublicUrl != "" {
		contexts := make([]interface{}, 1)
		imageJSON := simplejson.New()
		imageJSON.Set("type", "image")
		imageJSON.Set("src", evalContext.ImagePublicUrl)
		contexts[0] = imageJSON
		bodyJSON.Set("contexts", contexts)
	}

	body, _ := bodyJSON.MarshalJSON()

	cmd := &m.SendWebhookSync{
		Url:        pagerdutyEventApiUrl,
		Body:       string(body),
		HttpMethod: "POST",
	}

	if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
		this.log.Error("Failed to send notification to Pagerduty", "error", err, "body", string(body))
		return err
	}

	return nil
}
开发者ID:yuvaraj951,项目名称:grafana,代码行数:53,代码来源:pagerduty.go

示例2: Notify

func (this *TelegramNotifier) Notify(evalContext *alerting.EvalContext) error {
	this.log.Info("Sending alert notification to", "bot_token", this.BotToken)
	this.log.Info("Sending alert notification to", "chat_id", this.ChatID)
	metrics.M_Alerting_Notification_Sent_Telegram.Inc(1)

	bodyJSON := simplejson.New()

	bodyJSON.Set("chat_id", this.ChatID)
	bodyJSON.Set("parse_mode", "html")

	message := fmt.Sprintf("%s\nState: %s\nMessage: %s\n", evalContext.GetNotificationTitle(), evalContext.Rule.Name, evalContext.Rule.Message)

	ruleUrl, err := evalContext.GetRuleUrl()
	if err == nil {
		message = message + fmt.Sprintf("URL: %s\n", ruleUrl)
	}
	bodyJSON.Set("text", message)

	url := fmt.Sprintf(telegeramApiUrl, this.BotToken, "sendMessage")
	body, _ := bodyJSON.MarshalJSON()

	cmd := &m.SendWebhookSync{
		Url:        url,
		Body:       string(body),
		HttpMethod: "POST",
	}

	if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
		this.log.Error("Failed to send webhook", "error", err, "webhook", this.Name)
		return err
	}

	return nil
}
开发者ID:yuvaraj951,项目名称:grafana,代码行数:34,代码来源:telegram.go

示例3: Notify

func (this *WebhookNotifier) Notify(evalContext *alerting.EvalContext) error {
	this.log.Info("Sending webhook")
	metrics.M_Alerting_Notification_Sent_Webhook.Inc(1)

	bodyJSON := simplejson.New()
	bodyJSON.Set("title", evalContext.GetNotificationTitle())
	bodyJSON.Set("ruleId", evalContext.Rule.Id)
	bodyJSON.Set("ruleName", evalContext.Rule.Name)
	bodyJSON.Set("state", evalContext.Rule.State)
	bodyJSON.Set("evalMatches", evalContext.EvalMatches)

	ruleUrl, err := evalContext.GetRuleUrl()
	if err == nil {
		bodyJSON.Set("rule_url", ruleUrl)
	}

	if evalContext.ImagePublicUrl != "" {
		bodyJSON.Set("image_url", evalContext.ImagePublicUrl)
	}

	body, _ := bodyJSON.MarshalJSON()

	cmd := &m.SendWebhookSync{
		Url:      this.Url,
		User:     this.User,
		Password: this.Password,
		Body:     string(body),
	}

	if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
		this.log.Error("Failed to send webhook", "error", err, "webhook", this.Name)
	}

	return nil
}
开发者ID:roman-vynar,项目名称:grafana,代码行数:35,代码来源:webhook.go

示例4: createRequest

func (e *apiClient) createRequest(query string) (*http.Request, error) {
	u, err := url.Parse(e.Url)
	if err != nil {
		return nil, err
	}

	u.Path = path.Join(u.Path, "query")

	payload := simplejson.New()
	payload.Set("query", query)

	jsonPayload, err := payload.MarshalJSON()
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(string(jsonPayload)))
	if err != nil {
		return nil, err
	}

	req.Header.Set("User-Agent", "Grafana")
	req.Header.Set("Content-Type", "application/json")

	if e.BasicAuth {
		req.SetBasicAuth(e.BasicAuthUser, e.BasicAuthPassword)
	}

	return req, nil
}
开发者ID:mapr,项目名称:grafana,代码行数:30,代码来源:httpClient.go

示例5: Handle

func (handler *DefaultResultHandler) Handle(evalContext *EvalContext) error {
	executionError := ""
	annotationData := simplejson.New()

	evalContext.Rule.State = handler.GetStateFromEvaluation(evalContext)

	if evalContext.Error != nil {
		executionError = evalContext.Error.Error()
		annotationData.Set("errorMessage", executionError)
	}

	if evalContext.Firing {
		annotationData = simplejson.NewFromAny(evalContext.EvalMatches)
	}

	countStateResult(evalContext.Rule.State)
	if evalContext.ShouldUpdateAlertState() {
		handler.log.Info("New state change", "alertId", evalContext.Rule.Id, "newState", evalContext.Rule.State, "prev state", evalContext.PrevAlertState)

		cmd := &m.SetAlertStateCommand{
			AlertId:  evalContext.Rule.Id,
			OrgId:    evalContext.Rule.OrgId,
			State:    evalContext.Rule.State,
			Error:    executionError,
			EvalData: annotationData,
		}

		if err := bus.Dispatch(cmd); err != nil {
			handler.log.Error("Failed to save state", "error", err)
		}

		// save annotation
		item := annotations.Item{
			OrgId:       evalContext.Rule.OrgId,
			DashboardId: evalContext.Rule.DashboardId,
			PanelId:     evalContext.Rule.PanelId,
			Type:        annotations.AlertType,
			AlertId:     evalContext.Rule.Id,
			Title:       evalContext.Rule.Name,
			Text:        evalContext.GetStateModel().Text,
			NewState:    string(evalContext.Rule.State),
			PrevState:   string(evalContext.PrevAlertState),
			Epoch:       time.Now().Unix(),
			Data:        annotationData,
		}

		annotationRepo := annotations.GetRepository()
		if err := annotationRepo.Save(&item); err != nil {
			handler.log.Error("Failed to save annotation for new alert state", "error", err)
		}

		if evalContext.ShouldSendNotification() {
			handler.notifier.Notify(evalContext)
		}
	}

	return nil
}
开发者ID:utkarshcmu,项目名称:grafana,代码行数:58,代码来源:result_handler.go

示例6: NewDashboard

// NewDashboard creates a new dashboard
func NewDashboard(title string) *Dashboard {
	dash := &Dashboard{}
	dash.Data = simplejson.New()
	dash.Data.Set("title", title)
	dash.Title = title
	dash.Created = time.Now()
	dash.Updated = time.Now()
	dash.UpdateSlug()
	return dash
}
开发者ID:CamJN,项目名称:grafana,代码行数:11,代码来源:dashboards.go

示例7: Notify

func (this *SensuNotifier) Notify(evalContext *alerting.EvalContext) error {
	this.log.Info("Sending sensu result")
	metrics.M_Alerting_Notification_Sent_Sensu.Inc(1)

	bodyJSON := simplejson.New()
	bodyJSON.Set("ruleId", evalContext.Rule.Id)
	// Sensu alerts cannot have spaces in them
	bodyJSON.Set("name", strings.Replace(evalContext.Rule.Name, " ", "_", -1))
	// Sensu alerts require a command
	// We set it to the grafana ruleID
	bodyJSON.Set("source", "grafana_rule_"+strconv.FormatInt(evalContext.Rule.Id, 10))
	// Finally, sensu expects an output
	// We set it to a default output
	bodyJSON.Set("output", "Grafana Metric Condition Met")
	bodyJSON.Set("evalMatches", evalContext.EvalMatches)

	if evalContext.Rule.State == "alerting" {
		bodyJSON.Set("status", 2)
	} else if evalContext.Rule.State == "no_data" {
		bodyJSON.Set("status", 1)
	} else {
		bodyJSON.Set("status", 0)
	}

	ruleUrl, err := evalContext.GetRuleUrl()
	if err == nil {
		bodyJSON.Set("ruleUrl", ruleUrl)
	}

	if evalContext.ImagePublicUrl != "" {
		bodyJSON.Set("imageUrl", evalContext.ImagePublicUrl)
	}

	if evalContext.Rule.Message != "" {
		bodyJSON.Set("message", evalContext.Rule.Message)
	}

	body, _ := bodyJSON.MarshalJSON()

	cmd := &m.SendWebhookSync{
		Url:        this.Url,
		User:       this.User,
		Password:   this.Password,
		Body:       string(body),
		HttpMethod: "POST",
	}

	if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
		this.log.Error("Failed to send sensu event", "error", err, "sensu", this.Name)
		return err
	}

	return nil
}
开发者ID:yuvaraj951,项目名称:grafana,代码行数:54,代码来源:sensu.go

示例8: TestPluginDashboards

func TestPluginDashboards(t *testing.T) {

	Convey("When asking plugin dashboard info", t, func() {
		setting.Cfg = ini.Empty()
		sec, _ := setting.Cfg.NewSection("plugin.test-app")
		sec.NewKey("path", "../../tests/test-app")
		err := Init()

		So(err, ShouldBeNil)

		bus.AddHandler("test", func(query *m.GetDashboardQuery) error {
			if query.Slug == "nginx-connections" {
				dash := m.NewDashboard("Nginx Connections")
				dash.Data.Set("revision", "1.1")
				query.Result = dash
				return nil
			}

			return m.ErrDashboardNotFound
		})

		bus.AddHandler("test", func(query *m.GetDashboardsByPluginIdQuery) error {
			var data = simplejson.New()
			data.Set("title", "Nginx Connections")
			data.Set("revision", 22)

			query.Result = []*m.Dashboard{
				{Slug: "nginx-connections", Data: data},
			}
			return nil
		})

		dashboards, err := GetPluginDashboards(1, "test-app")

		So(err, ShouldBeNil)

		Convey("should return 2 dashboarrd", func() {
			So(len(dashboards), ShouldEqual, 2)
		})

		Convey("should include installed version info", func() {
			So(dashboards[0].Title, ShouldEqual, "Nginx Connections")
			So(dashboards[0].Revision, ShouldEqual, 25)
			So(dashboards[0].ImportedRevision, ShouldEqual, 22)
			So(dashboards[0].ImportedUri, ShouldEqual, "db/nginx-connections")

			So(dashboards[1].Revision, ShouldEqual, 2)
			So(dashboards[1].ImportedRevision, ShouldEqual, 0)
		})
	})

}
开发者ID:Robin7Ma,项目名称:grafana,代码行数:52,代码来源:dashboards_test.go

示例9: createAlert

func (this *OpsGenieNotifier) createAlert(evalContext *alerting.EvalContext) error {
	this.log.Info("Creating OpsGenie alert", "ruleId", evalContext.Rule.Id, "notification", this.Name)

	ruleUrl, err := evalContext.GetRuleUrl()
	if err != nil {
		this.log.Error("Failed get rule link", "error", err)
		return err
	}

	bodyJSON := simplejson.New()
	bodyJSON.Set("apiKey", this.ApiKey)
	bodyJSON.Set("message", evalContext.Rule.Name)
	bodyJSON.Set("source", "Grafana")
	bodyJSON.Set("alias", "alertId-"+strconv.FormatInt(evalContext.Rule.Id, 10))
	bodyJSON.Set("description", fmt.Sprintf("%s - %s\n%s", evalContext.Rule.Name, ruleUrl, evalContext.Rule.Message))

	details := simplejson.New()
	details.Set("url", ruleUrl)
	if evalContext.ImagePublicUrl != "" {
		details.Set("image", evalContext.ImagePublicUrl)
	}

	bodyJSON.Set("details", details)
	body, _ := bodyJSON.MarshalJSON()

	cmd := &m.SendWebhookSync{
		Url:        opsgenieCreateAlertURL,
		Body:       string(body),
		HttpMethod: "POST",
	}

	if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
		this.log.Error("Failed to send notification to OpsGenie", "error", err, "body", string(body))
	}

	return nil
}
开发者ID:yuvaraj951,项目名称:grafana,代码行数:37,代码来源:opsgenie.go

示例10: TestTokenClient

func TestTokenClient(t *testing.T) {
	SkipConvey("Token client", t, func() {
		dsInfo := &models.DataSource{
			JsonData: simplejson.New(),
			Url:      "",
		}

		client := NewTokenClient(dsInfo)

		body, err := client.RequestTokenData(context.TODO())

		So(err, ShouldBeNil)
		//So(len(body.Functions), ShouldBeGreaterThan, 1)
		So(len(body.Metrics), ShouldBeGreaterThan, 1)
	})
}
开发者ID:yuvaraj951,项目名称:grafana,代码行数:16,代码来源:token_client_test.go

示例11: closeAlert

func (this *OpsGenieNotifier) closeAlert(evalContext *alerting.EvalContext) error {
	this.log.Info("Closing OpsGenie alert", "ruleId", evalContext.Rule.Id, "notification", this.Name)

	bodyJSON := simplejson.New()
	bodyJSON.Set("apiKey", this.ApiKey)
	bodyJSON.Set("alias", "alertId-"+strconv.FormatInt(evalContext.Rule.Id, 10))
	body, _ := bodyJSON.MarshalJSON()

	cmd := &m.SendWebhookSync{
		Url:        opsgenieCloseAlertURL,
		Body:       string(body),
		HttpMethod: "POST",
	}

	if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {
		this.log.Error("Failed to send notification to OpsGenie", "error", err, "body", string(body))
	}

	return nil
}
开发者ID:CamJN,项目名称:grafana,代码行数:20,代码来源:opsgenie.go

示例12: Eval

func (this *DashTemplateEvaluator) Eval() (*simplejson.Json, error) {
	this.result = simplejson.New()
	this.variables = make(map[string]string)
	this.varRegex, _ = regexp.Compile(`(\$\{\w+\})`)

	// check that we have all inputs we need
	for _, inputDef := range this.template.Get("__inputs").MustArray() {
		inputDefJson := simplejson.NewFromAny(inputDef)
		inputName := inputDefJson.Get("name").MustString()
		inputType := inputDefJson.Get("type").MustString()
		input := this.findInput(inputName, inputType)

		if input == nil {
			return nil, &DashboardInputMissingError{VariableName: inputName}
		}

		this.variables["${"+inputName+"}"] = input.Value
	}

	return simplejson.NewFromAny(this.evalObject(this.template)), nil
}
开发者ID:seizadi,项目名称:grafana,代码行数:21,代码来源:dashboard_importer.go

示例13: TestDashboardModel

func TestDashboardModel(t *testing.T) {

	Convey("When generating slug", t, func() {
		dashboard := NewDashboard("Grafana Play Home")
		dashboard.UpdateSlug()

		So(dashboard.Slug, ShouldEqual, "grafana-play-home")
	})

	Convey("Given a dashboard json", t, func() {
		json := simplejson.New()
		json.Set("title", "test dash")

		Convey("With tags as string value", func() {
			json.Set("tags", "")
			dash := NewDashboardFromJson(json)

			So(len(dash.GetTags()), ShouldEqual, 0)
		})
	})

}
开发者ID:Robin7Ma,项目名称:grafana,代码行数:22,代码来源:dashboards_test.go

示例14: TestMQEQueryParser

func TestMQEQueryParser(t *testing.T) {
	Convey("MQE query parser", t, func() {
		parser := &QueryParser{}

		dsInfo := &models.DataSource{JsonData: simplejson.New()}
		queryContext := &tsdb.QueryContext{}

		Convey("can parse simple mqe model", func() {
			json := `
      {
        "cluster": [],
        "hosts": [
          "staples-lab-1"
        ],
        "metrics": [
          {
            "metric": "os.cpu.all*"
          }
        ],
        "rawQuery": "",
        "refId": "A"
      }
      `
			modelJson, err := simplejson.NewJson([]byte(json))
			So(err, ShouldBeNil)

			query, err := parser.Parse(modelJson, dsInfo, queryContext)
			So(err, ShouldBeNil)
			So(query.UseRawQuery, ShouldBeFalse)

			So(len(query.Cluster), ShouldEqual, 0)
			So(query.Hosts[0], ShouldEqual, "staples-lab-1")
			So(query.Metrics[0].Metric, ShouldEqual, "os.cpu.all*")
		})

		Convey("can parse multi serie mqe model", func() {
			json := `
      {
        "cluster": [
          "demoapp"
        ],
        "hosts": [
          "staples-lab-1"
        ],
        "metrics": [
          {
            "metric": "os.cpu.all.active_percentage"
          },
          {
            "metric": "os.disk.sda.io_time"
          }
        ],
        "functionList": [
          {
            "func": "aggregate.min"
          },
          {
             "func": "aggregate.max"
          }
        ],
        "rawQuery": "",
        "refId": "A",
        "addClusterToAlias": true,
        "addHostToAlias": true
      }
      `
			modelJson, err := simplejson.NewJson([]byte(json))
			So(err, ShouldBeNil)

			query, err := parser.Parse(modelJson, dsInfo, queryContext)
			So(err, ShouldBeNil)
			So(query.UseRawQuery, ShouldBeFalse)
			So(query.Cluster[0], ShouldEqual, "demoapp")
			So(query.Metrics[0].Metric, ShouldEqual, "os.cpu.all.active_percentage")
			So(query.Metrics[1].Metric, ShouldEqual, "os.disk.sda.io_time")
			So(query.FunctionList[0].Func, ShouldEqual, "aggregate.min")
			So(query.FunctionList[1].Func, ShouldEqual, "aggregate.max")
		})

		Convey("can parse raw query", func() {
			json := `
      {
        "addClusterToAlias": true,
        "addHostToAlias": true,
        "cluster": [],
        "hosts": [
          "staples-lab-1"
        ],
        "metrics": [
          {
            "alias": "cpu active",
            "metric": "os.cpu.all.active_percentage"
          },
          {
            "alias": "disk sda time",
            "metric": "os.disk.sda.io_time"
          }
        ],
        "rawQuery": true,
        "query": "raw-query",
//.........这里部分代码省略.........
开发者ID:mapr,项目名称:grafana,代码行数:101,代码来源:model_parser_test.go

示例15: Handle

func (handler *DefaultResultHandler) Handle(evalContext *EvalContext) error {
	oldState := evalContext.Rule.State

	executionError := ""
	annotationData := simplejson.New()
	if evalContext.Error != nil {
		handler.log.Error("Alert Rule Result Error", "ruleId", evalContext.Rule.Id, "error", evalContext.Error)
		evalContext.Rule.State = m.AlertStateExecError
		executionError = evalContext.Error.Error()
		annotationData.Set("errorMessage", executionError)
	} else if evalContext.Firing {
		evalContext.Rule.State = m.AlertStateAlerting
		annotationData = simplejson.NewFromAny(evalContext.EvalMatches)
	} else {
		if evalContext.NoDataFound {
			if evalContext.Rule.NoDataState != m.NoDataKeepState {
				evalContext.Rule.State = evalContext.Rule.NoDataState.ToAlertState()
			}
		} else {
			evalContext.Rule.State = m.AlertStateOK
		}
	}

	countStateResult(evalContext.Rule.State)
	if handler.shouldUpdateAlertState(evalContext, oldState) {
		handler.log.Info("New state change", "alertId", evalContext.Rule.Id, "newState", evalContext.Rule.State, "oldState", oldState)

		cmd := &m.SetAlertStateCommand{
			AlertId:  evalContext.Rule.Id,
			OrgId:    evalContext.Rule.OrgId,
			State:    evalContext.Rule.State,
			Error:    executionError,
			EvalData: annotationData,
		}

		if err := bus.Dispatch(cmd); err != nil {
			handler.log.Error("Failed to save state", "error", err)
		}

		// save annotation
		item := annotations.Item{
			OrgId:       evalContext.Rule.OrgId,
			DashboardId: evalContext.Rule.DashboardId,
			PanelId:     evalContext.Rule.PanelId,
			Type:        annotations.AlertType,
			AlertId:     evalContext.Rule.Id,
			Title:       evalContext.Rule.Name,
			Text:        evalContext.GetStateModel().Text,
			NewState:    string(evalContext.Rule.State),
			PrevState:   string(oldState),
			Epoch:       time.Now().Unix(),
			Data:        annotationData,
		}

		annotationRepo := annotations.GetRepository()
		if err := annotationRepo.Save(&item); err != nil {
			handler.log.Error("Failed to save annotation for new alert state", "error", err)
		}

		if (oldState == m.AlertStatePending) && (evalContext.Rule.State == m.AlertStateOK) {
			handler.log.Info("Notfication not sent", "oldState", oldState, "newState", evalContext.Rule.State)
		} else {
			handler.notifier.Notify(evalContext)
		}

	}

	return nil
}
开发者ID:wk66,项目名称:grafana,代码行数:69,代码来源:result_handler.go


注:本文中的github.com/grafana/grafana/pkg/components/simplejson.New函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。