本文整理匯總了Golang中github.com/grafana/grafana/pkg/middleware.Context.JsonApiErr方法的典型用法代碼示例。如果您正苦於以下問題:Golang Context.JsonApiErr方法的具體用法?Golang Context.JsonApiErr怎麽用?Golang Context.JsonApiErr使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/grafana/grafana/pkg/middleware.Context
的用法示例。
在下文中一共展示了Context.JsonApiErr方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: CreateDashboardSnapshot
func CreateDashboardSnapshot(c *middleware.Context, cmd m.CreateDashboardSnapshotCommand) {
if cmd.External {
// external snapshot ref requires key and delete key
if cmd.Key == "" || cmd.DeleteKey == "" {
c.JsonApiErr(400, "Missing key and delete key for external snapshot", nil)
return
}
cmd.OrgId = -1
cmd.UserId = -1
metrics.M_Api_Dashboard_Snapshot_External.Inc(1)
} else {
cmd.Key = util.GetRandomString(32)
cmd.DeleteKey = util.GetRandomString(32)
cmd.OrgId = c.OrgId
cmd.UserId = c.UserId
metrics.M_Api_Dashboard_Snapshot_Create.Inc(1)
}
if err := bus.Dispatch(&cmd); err != nil {
c.JsonApiErr(500, "Failed to create snaphost", err)
return
}
c.JSON(200, util.DynMap{
"key": cmd.Key,
"deleteKey": cmd.DeleteKey,
"url": setting.ToAbsUrl("dashboard/snapshot/" + cmd.Key),
"deleteUrl": setting.ToAbsUrl("api/snapshots-delete/" + cmd.DeleteKey),
})
}
示例2: GraphiteProxy
func GraphiteProxy(c *middleware.Context) {
proxyPath := c.Params("*")
target, _ := url.Parse(setting.GraphiteUrl)
// check if this is a special raintank_db requests
if proxyPath == "metrics/find" {
query := c.Query("query")
if strings.HasPrefix(query, "raintank_db") {
response, err := executeRaintankDbQuery(query, c.OrgId)
if err != nil {
c.JsonApiErr(500, "Failed to execute raintank_db query", err)
return
}
c.JSON(200, response)
return
}
}
director := func(req *http.Request) {
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.Header.Add("X-Org-Id", strconv.FormatInt(c.OrgId, 10))
req.URL.Path = util.JoinUrlFragments(target.Path, proxyPath)
}
proxy := &httputil.ReverseProxy{Director: director}
proxy.ServeHTTP(c.RW(), c.Req.Request)
}
示例3: LoginPost
func LoginPost(c *middleware.Context, cmd dtos.LoginCommand) {
userQuery := m.GetUserByLoginQuery{LoginOrEmail: cmd.User}
err := bus.Dispatch(&userQuery)
if err != nil {
c.JsonApiErr(401, "Invalid username or password", err)
return
}
user := userQuery.Result
passwordHashed := util.EncodePassword(cmd.Password, user.Salt)
if passwordHashed != user.Password {
c.JsonApiErr(401, "Invalid username or password", err)
return
}
loginUserWithUser(user, c)
result := map[string]interface{}{
"message": "Logged in",
}
if redirectTo, _ := url.QueryUnescape(c.GetCookie("redirect_to")); len(redirectTo) > 0 {
result["redirectUrl"] = redirectTo
c.SetCookie("redirect_to", "", -1, setting.AppSubUrl+"/")
}
metrics.M_Api_Login_Post.Inc(1)
c.JSON(200, result)
}
示例4: handleListMetrics
func handleListMetrics(req *cwRequest, c *middleware.Context) {
creds := credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: req.DataSource.Database},
&ec2rolecreds.EC2RoleProvider{ExpiryWindow: 5 * time.Minute},
})
svc := cloudwatch.New(&aws.Config{
Region: aws.String(req.Region),
Credentials: creds,
})
reqParam := &struct {
Parameters struct {
Namespace string `json:"namespace"`
MetricName string `json:"metricName"`
Dimensions []*cloudwatch.DimensionFilter `json:"dimensions"`
} `json:"parameters"`
}{}
json.Unmarshal(req.Body, reqParam)
params := &cloudwatch.ListMetricsInput{
Namespace: aws.String(reqParam.Parameters.Namespace),
MetricName: aws.String(reqParam.Parameters.MetricName),
Dimensions: reqParam.Parameters.Dimensions,
}
resp, err := svc.ListMetrics(params)
if err != nil {
c.JsonApiErr(500, "Unable to call AWS API", err)
return
}
c.JSON(200, resp)
}
示例5: GetDataSourceById
func GetDataSourceById(c *middleware.Context) {
query := m.GetDataSourceByIdQuery{
Id: c.ParamsInt64(":id"),
OrgId: c.OrgId,
}
if err := bus.Dispatch(&query); err != nil {
c.JsonApiErr(500, "Failed to query datasources", err)
return
}
ds := query.Result
c.JSON(200, &dtos.DataSource{
Id: ds.Id,
OrgId: ds.OrgId,
Name: ds.Name,
Url: ds.Url,
Type: ds.Type,
Access: ds.Access,
Password: ds.Password,
Database: ds.Database,
User: ds.User,
BasicAuth: ds.BasicAuth,
BasicAuthUser: ds.BasicAuthUser,
BasicAuthPassword: ds.BasicAuthPassword,
IsDefault: ds.IsDefault,
JsonData: ds.JsonData,
})
}
示例6: ProxyDataSourceRequest
//ProxyDataSourceRequest TODO need to cache datasources
func ProxyDataSourceRequest(c *middleware.Context) {
id := c.ParamsInt64(":id")
query := m.GetDataSourceByIdQuery{Id: id, OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil {
c.JsonApiErr(500, "Unable to load datasource meta data", err)
return
}
ds := query.Result
targetUrl, _ := url.Parse(ds.Url)
if len(setting.DataProxyWhiteList) > 0 {
if _, exists := setting.DataProxyWhiteList[targetUrl.Host]; !exists {
c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
return
}
}
if query.Result.Type == m.DS_CLOUDWATCH {
cloudwatch.HandleRequest(c)
} else {
proxyPath := c.Params("*")
proxy := NewReverseProxy(&ds, proxyPath, targetUrl)
proxy.Transport = dataProxyTransport
proxy.ServeHTTP(c.RW(), c.Req.Request)
}
}
示例7: PostDashboard
func PostDashboard(c *middleware.Context, cmd m.SaveDashboardCommand) {
cmd.OrgId = c.OrgId
err := bus.Dispatch(&cmd)
if err != nil {
if err == m.ErrDashboardWithSameNameExists {
c.JSON(412, util.DynMap{"status": "name-exists", "message": err.Error()})
return
}
if err == m.ErrDashboardVersionMismatch {
c.JSON(412, util.DynMap{"status": "version-mismatch", "message": err.Error()})
return
}
if err == m.ErrDashboardNotFound {
c.JSON(404, util.DynMap{"status": "not-found", "message": err.Error()})
return
}
c.JsonApiErr(500, "Failed to save dashboard", err)
return
}
metrics.M_Api_Dashboard_Post.Inc(1)
c.JSON(200, util.DynMap{"status": "success", "slug": cmd.Result.Slug, "version": cmd.Result.Version})
}
示例8: handleGetMetrics
func handleGetMetrics(req *cwRequest, c *middleware.Context) {
reqParam := &struct {
Parameters struct {
Namespace string `json:"namespace"`
} `json:"parameters"`
}{}
json.Unmarshal(req.Body, reqParam)
var namespaceMetrics []string
if !isCustomMetrics(reqParam.Parameters.Namespace) {
var exists bool
if namespaceMetrics, exists = metricsMap[reqParam.Parameters.Namespace]; !exists {
c.JsonApiErr(404, "Unable to find namespace "+reqParam.Parameters.Namespace, nil)
return
}
} else {
var err error
cwData := req.GetDatasourceInfo()
cwData.Namespace = reqParam.Parameters.Namespace
if namespaceMetrics, err = getMetricsForCustomMetrics(cwData, getAllMetrics); err != nil {
c.JsonApiErr(500, "Unable to call AWS API", err)
return
}
}
sort.Sort(sort.StringSlice(namespaceMetrics))
result := []interface{}{}
for _, name := range namespaceMetrics {
result = append(result, util.DynMap{"text": name, "value": name})
}
c.JSON(200, result)
}
示例9: handleListMetrics
func handleListMetrics(req *cwRequest, c *middleware.Context) {
cfg := getAwsConfig(req)
svc := cloudwatch.New(session.New(cfg), cfg)
reqParam := &struct {
Parameters struct {
Namespace string `json:"namespace"`
MetricName string `json:"metricName"`
Dimensions []*cloudwatch.DimensionFilter `json:"dimensions"`
} `json:"parameters"`
}{}
json.Unmarshal(req.Body, reqParam)
params := &cloudwatch.ListMetricsInput{
Namespace: aws.String(reqParam.Parameters.Namespace),
MetricName: aws.String(reqParam.Parameters.MetricName),
Dimensions: reqParam.Parameters.Dimensions,
}
var resp cloudwatch.ListMetricsOutput
err := svc.ListMetricsPages(params,
func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool {
metrics, _ := awsutil.ValuesAtPath(page, "Metrics")
for _, metric := range metrics {
resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric))
}
return !lastPage
})
if err != nil {
c.JsonApiErr(500, "Unable to call AWS API", err)
return
}
c.JSON(200, resp)
}
示例10: handleDescribeAlarmHistory
func handleDescribeAlarmHistory(req *cwRequest, c *middleware.Context) {
cfg := &aws.Config{
Region: aws.String(req.Region),
Credentials: getCredentials(req.DataSource.Database),
}
svc := cloudwatch.New(session.New(cfg), cfg)
reqParam := &struct {
Parameters struct {
AlarmName string `json:"alarmName"`
HistoryItemType string `json:"historyItemType"`
StartDate int64 `json:"startDate"`
EndDate int64 `json:"endDate"`
} `json:"parameters"`
}{}
json.Unmarshal(req.Body, reqParam)
params := &cloudwatch.DescribeAlarmHistoryInput{
AlarmName: aws.String(reqParam.Parameters.AlarmName),
StartDate: aws.Time(time.Unix(reqParam.Parameters.StartDate, 0)),
EndDate: aws.Time(time.Unix(reqParam.Parameters.EndDate, 0)),
}
if reqParam.Parameters.HistoryItemType != "" {
params.HistoryItemType = aws.String(reqParam.Parameters.HistoryItemType)
}
resp, err := svc.DescribeAlarmHistory(params)
if err != nil {
c.JsonApiErr(500, "Unable to call AWS API", err)
return
}
c.JSON(200, resp)
}
示例11: handleDescribeAlarmsForMetric
func handleDescribeAlarmsForMetric(req *cwRequest, c *middleware.Context) {
cfg := getAwsConfig(req)
svc := cloudwatch.New(session.New(cfg), cfg)
reqParam := &struct {
Parameters struct {
Namespace string `json:"namespace"`
MetricName string `json:"metricName"`
Dimensions []*cloudwatch.Dimension `json:"dimensions"`
Statistic string `json:"statistic"`
Period int64 `json:"period"`
} `json:"parameters"`
}{}
json.Unmarshal(req.Body, reqParam)
params := &cloudwatch.DescribeAlarmsForMetricInput{
Namespace: aws.String(reqParam.Parameters.Namespace),
MetricName: aws.String(reqParam.Parameters.MetricName),
Period: aws.Int64(reqParam.Parameters.Period),
}
if len(reqParam.Parameters.Dimensions) != 0 {
params.Dimensions = reqParam.Parameters.Dimensions
}
if reqParam.Parameters.Statistic != "" {
params.Statistic = aws.String(reqParam.Parameters.Statistic)
}
resp, err := svc.DescribeAlarmsForMetric(params)
if err != nil {
c.JsonApiErr(500, "Unable to call AWS API", err)
return
}
c.JSON(200, resp)
}
示例12: ValidateOrgPlaylist
func ValidateOrgPlaylist(c *middleware.Context) {
id := c.ParamsInt64(":id")
query := m.GetPlaylistByIdQuery{Id: id}
err := bus.Dispatch(&query)
if err != nil {
c.JsonApiErr(404, "Playlist not found", err)
return
}
if query.Result.OrgId == 0 {
c.JsonApiErr(404, "Playlist not found", err)
return
}
if query.Result.OrgId != c.OrgId {
c.JsonApiErr(403, "You are not allowed to edit/view playlist", nil)
return
}
items, itemsErr := LoadPlaylistItemDTOs(id)
if itemsErr != nil {
c.JsonApiErr(404, "Playlist items not found", err)
return
}
if len(items) == 0 {
c.JsonApiErr(404, "Playlist is empty", itemsErr)
return
}
}
示例13: ProxyDataSourceRequest
func ProxyDataSourceRequest(c *middleware.Context) {
c.TimeRequest(metrics.M_DataSource_ProxyReq_Timer)
ds, err := getDatasource(c.ParamsInt64(":id"), c.OrgId)
if err != nil {
c.JsonApiErr(500, "Unable to load datasource meta data", err)
return
}
targetUrl, _ := url.Parse(ds.Url)
if len(setting.DataProxyWhiteList) > 0 {
if _, exists := setting.DataProxyWhiteList[targetUrl.Host]; !exists {
c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
return
}
}
if ds.Type == m.DS_CLOUDWATCH {
cloudwatch.HandleRequest(c, ds)
} else {
proxyPath := c.Params("*")
proxy := NewReverseProxy(ds, proxyPath, targetUrl)
proxy.Transport = dataProxyTransport
proxy.ServeHTTP(c.Resp, c.Req.Request)
c.Resp.Header().Del("Set-Cookie")
}
}
示例14: handleGetDimensions
func handleGetDimensions(req *cwRequest, c *middleware.Context) {
reqParam := &struct {
Parameters struct {
Namespace string `json:"namespace"`
} `json:"parameters"`
}{}
json.Unmarshal(req.Body, reqParam)
var dimensionValues []string
if !isCustomMetrics(reqParam.Parameters.Namespace) {
var exists bool
if dimensionValues, exists = dimensionsMap[reqParam.Parameters.Namespace]; !exists {
c.JsonApiErr(404, "Unable to find dimension "+reqParam.Parameters.Namespace, nil)
return
}
} else {
var err error
if dimensionValues, err = getDimensionsForCustomMetrics(req.Region, reqParam.Parameters.Namespace, req.DataSource.Database, getAllMetrics); err != nil {
c.JsonApiErr(500, "Unable to call AWS API", err)
return
}
}
sort.Sort(sort.StringSlice(dimensionValues))
result := []interface{}{}
for _, name := range dimensionValues {
result = append(result, util.DynMap{"text": name, "value": name})
}
c.JSON(200, result)
}
示例15: handleListMetrics
func handleListMetrics(req *cwRequest, c *middleware.Context) {
svc := cloudwatch.New(&aws.Config{Region: aws.String(req.Region)})
reqParam := &struct {
Parameters struct {
Namespace string `json:"namespace"`
MetricName string `json:"metricName"`
Dimensions []*cloudwatch.DimensionFilter `json:"dimensions"`
} `json:"parameters"`
}{}
json.Unmarshal(req.Body, reqParam)
params := &cloudwatch.ListMetricsInput{
Namespace: aws.String(reqParam.Parameters.Namespace),
MetricName: aws.String(reqParam.Parameters.MetricName),
Dimensions: reqParam.Parameters.Dimensions,
}
resp, err := svc.ListMetrics(params)
if err != nil {
c.JsonApiErr(500, "Unable to call AWS API", err)
return
}
c.JSON(200, resp)
}