本文整理汇总了Golang中github.com/grafana/grafana/pkg/middleware.Context类的典型用法代码示例。如果您正苦于以下问题:Golang Context类的具体用法?Golang Context怎么用?Golang Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Context类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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)
}
示例2: 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")
}
}
示例3: PauseAlert
//POST /api/alerts/:alertId/pause
func PauseAlert(c *middleware.Context, dto dtos.PauseAlertCommand) Response {
cmd := models.PauseAlertCommand{
OrgId: c.OrgId,
AlertId: c.ParamsInt64("alertId"),
Paused: dto.Paused,
}
if err := bus.Dispatch(&cmd); err != nil {
return ApiError(500, "", err)
}
var response models.AlertStateType = models.AlertStatePending
pausedState := "un paused"
if cmd.Paused {
response = models.AlertStatePaused
pausedState = "paused"
}
result := map[string]interface{}{
"alertId": cmd.AlertId,
"state": response,
"message": "alert " + pausedState,
}
return Json(200, result)
}
示例4: 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})
}
示例5: 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)
}
}
示例6: 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)
}
示例7: 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)
}
示例8: AdminUpdateUserPassword
func AdminUpdateUserPassword(c *middleware.Context, form dtos.AdminUpdateUserPasswordForm) {
userId := c.ParamsInt64(":id")
if len(form.Password) < 4 {
c.JsonApiErr(400, "New password too short", nil)
return
}
userQuery := m.GetUserByIdQuery{Id: userId}
if err := bus.Dispatch(&userQuery); err != nil {
c.JsonApiErr(500, "Could not read user from database", err)
return
}
passwordHashed := util.EncodePassword(form.Password, userQuery.Result.Salt)
cmd := m.ChangeUserPasswordCommand{
UserId: userId,
NewPassword: passwordHashed,
}
if err := bus.Dispatch(&cmd); err != nil {
c.JsonApiErr(500, "Failed to update user password", err)
return
}
c.JsonOK("User password updated")
}
示例9: GetPluginSettingById
func GetPluginSettingById(c *middleware.Context) Response {
pluginId := c.Params(":pluginId")
if def, exists := plugins.Plugins[pluginId]; !exists {
return ApiError(404, "Plugin not found, no installed plugin with that id", nil)
} else {
dto := &dtos.PluginSetting{
Type: def.Type,
Id: def.Id,
Name: def.Name,
Info: &def.Info,
Dependencies: &def.Dependencies,
Includes: def.Includes,
BaseUrl: def.BaseUrl,
Module: def.Module,
DefaultNavUrl: def.DefaultNavUrl,
LatestVersion: def.GrafanaNetVersion,
HasUpdate: def.GrafanaNetHasUpdate,
}
query := m.GetPluginSettingByIdQuery{PluginId: pluginId, OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil {
if err != m.ErrPluginSettingNotFound {
return ApiError(500, "Failed to get login settings", nil)
}
} else {
dto.Enabled = query.Result.Enabled
dto.Pinned = query.Result.Pinned
dto.JsonData = query.Result.JsonData
}
return Json(200, dto)
}
}
示例10: GetSubProcessById
func GetSubProcessById(c *middleware.Context) Response {
logger := log.New("main")
logger.Info("GetProcess123 %s")
subprocessId := c.ParamsInt64(":subProcessId")
logger.Info("GetProcess123 %s", subprocessId)
return getSubProcessUserProfile(subprocessId)
}
示例11: GetSubProcessByName
func GetSubProcessByName(c *middleware.Context) Response {
logger := log.New("main")
logger.Info("Get Sub Process1 %s")
processName := c.Params(":processName")
logger.Info("Get Sub Process 2 %s", processName)
return getSubProcessProfile(processName)
}
示例12: getAlertIdForRequest
func getAlertIdForRequest(c *middleware.Context) (int64, error) {
alertId := c.QueryInt64("alertId")
panelId := c.QueryInt64("panelId")
dashboardId := c.QueryInt64("dashboardId")
if alertId == 0 && dashboardId == 0 && panelId == 0 {
return 0, fmt.Errorf("Missing alertId or dashboardId and panelId")
}
if alertId == 0 {
//fetch alertId
query := models.GetAlertsQuery{
OrgId: c.OrgId,
DashboardId: dashboardId,
PanelId: panelId,
}
if err := bus.Dispatch(&query); err != nil {
return 0, err
}
if len(query.Result) != 1 {
return 0, fmt.Errorf("PanelId is not unique on dashboard")
}
alertId = query.Result[0].Id
}
return alertId, nil
}
示例13: 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)
}
示例14: UpdateOrgProcessForCurrentOrg
func UpdateOrgProcessForCurrentOrg(c *middleware.Context, cmd m.UpdateOrgProcessCommand) Response {
cmd.ProcessId = c.ParamsInt64(":processId")
logger := log.New("main")
logger.Info("updatedProcess1 %s")
return updateOrgProcessHelper(cmd)
}
示例15: RevokeInvite
func RevokeInvite(c *middleware.Context) Response {
if ok, rsp := updateTempUserStatus(c.Params(":code"), m.TmpUserRevoked); !ok {
return rsp
}
return ApiSuccess("Invite revoked")
}