mirror of
https://github.com/grafana/grafana.git
synced 2024-11-29 12:14:08 -06:00
6c5a573772
* Chore: Move ReqContext to contexthandler service * Rename package to contextmodel * Generate ngalert files * Remove unused imports
66 lines
2.0 KiB
Go
66 lines
2.0 KiB
Go
package api
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/grafana/grafana/pkg/api/dtos"
|
|
"github.com/grafana/grafana/pkg/api/response"
|
|
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
|
|
"github.com/grafana/grafana/pkg/services/shorturls"
|
|
"github.com/grafana/grafana/pkg/setting"
|
|
"github.com/grafana/grafana/pkg/util"
|
|
"github.com/grafana/grafana/pkg/web"
|
|
)
|
|
|
|
// createShortURL handles requests to create short URLs.
|
|
func (hs *HTTPServer) createShortURL(c *contextmodel.ReqContext) response.Response {
|
|
cmd := dtos.CreateShortURLCmd{}
|
|
if err := web.Bind(c.Req, &cmd); err != nil {
|
|
return response.Err(shorturls.ErrShortURLBadRequest.Errorf("bad request data: %w", err))
|
|
}
|
|
hs.log.Debug("Received request to create short URL", "path", cmd.Path)
|
|
shortURL, err := hs.ShortURLService.CreateShortURL(c.Req.Context(), c.SignedInUser, cmd.Path)
|
|
if err != nil {
|
|
return response.Err(err)
|
|
}
|
|
|
|
url := fmt.Sprintf("%s/goto/%s?orgId=%d", strings.TrimSuffix(setting.AppUrl, "/"), shortURL.Uid, c.OrgID)
|
|
c.Logger.Debug("Created short URL", "url", url)
|
|
|
|
dto := dtos.ShortURL{
|
|
UID: shortURL.Uid,
|
|
URL: url,
|
|
}
|
|
|
|
return response.JSON(http.StatusOK, dto)
|
|
}
|
|
|
|
func (hs *HTTPServer) redirectFromShortURL(c *contextmodel.ReqContext) {
|
|
shortURLUID := web.Params(c.Req)[":uid"]
|
|
|
|
if !util.IsValidShortUID(shortURLUID) {
|
|
return
|
|
}
|
|
|
|
shortURL, err := hs.ShortURLService.GetShortURLByUID(c.Req.Context(), c.SignedInUser, shortURLUID)
|
|
if err != nil {
|
|
if shorturls.ErrShortURLNotFound.Is(err) {
|
|
hs.log.Debug("Not redirecting short URL since not found")
|
|
return
|
|
}
|
|
|
|
hs.log.Error("Short URL redirection error", "err", err)
|
|
return
|
|
}
|
|
|
|
// Failure to update LastSeenAt should still allow to redirect
|
|
if err := hs.ShortURLService.UpdateLastSeenAt(c.Req.Context(), shortURL); err != nil {
|
|
hs.log.Error("Failed to update short URL last seen at", "error", err)
|
|
}
|
|
|
|
hs.log.Debug("Redirecting short URL", "path", shortURL.Path)
|
|
c.Redirect(setting.ToAbsUrl(shortURL.Path), 302)
|
|
}
|