Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Native short links in bosun #2210

Merged
merged 2 commits into from
Feb 18, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions cmd/bosun/conf/system.go
Original file line number Diff line number Diff line change
Expand Up @@ -541,10 +541,12 @@ func (sc *SystemConf) AnnotateEnabled() bool {
// MakeLink creates a HTML Link based on Bosun's configured Hostname
func (sc *SystemConf) MakeLink(path string, v *url.Values) string {
u := url.URL{
Scheme: sc.Scheme,
Host: sc.Hostname,
Path: path,
RawQuery: v.Encode(),
Scheme: sc.Scheme,
Host: sc.Hostname,
Path: path,
}
if v != nil {
u.RawQuery = v.Encode()
}
return u.String()
}
Expand Down
34 changes: 34 additions & 0 deletions cmd/bosun/database/config_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package database
import (
"crypto/md5"
"encoding/base64"
"fmt"

"github.com/garyburd/redigo/redis"

Expand All @@ -12,6 +13,9 @@ import (
type ConfigDataAccess interface {
SaveTempConfig(text string) (hash string, err error)
GetTempConfig(hash string) (text string, err error)

ShortenLink(fullURL string) (id int, err error)
GetShortLink(id int) (fullURL string, err error)
}

func (d *dataAccess) Configs() ConfigDataAccess {
Expand Down Expand Up @@ -46,3 +50,33 @@ func (d *dataAccess) GetTempConfig(hash string) (string, error) {
_, err = conn.Do("EXPIRE", key, configLifetime)
return dat, slog.Wrap(err)
}

const (
shortLinkCounterKey = "shortlinkCount"
shortLinksKey = "shortLinks"
)

func (d *dataAccess) ShortenLink(fullURL string) (id int, err error) {
conn := d.Get()
defer conn.Close()

newID, err := redis.Int(conn.Do("INCR", shortLinkCounterKey))
if err != nil {
return 0, slog.Wrap(err)
}
if _, err := conn.Do("HSET", shortLinksKey, fmt.Sprint(newID), fullURL); err != nil {
return 0, slog.Wrap(err)
}
return newID, nil
}

func (d *dataAccess) GetShortLink(id int) (fullURL string, err error) {
conn := d.Get()
defer conn.Close()

s, err := redis.String(conn.Do("HGET", shortLinksKey, fmt.Sprint(id)))
if err != nil {
return "", slog.Wrap(err)
}
return s, nil
}
46 changes: 17 additions & 29 deletions cmd/bosun/web/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"html/template"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httputil"
"net/url"
Expand Down Expand Up @@ -171,6 +170,7 @@ func Listen(httpAddr, httpsAddr, certFile, keyFile string, devMode bool, tsdbHos
handle("/api/rule", JSON(Rule), canRunTests).Name("rule_test").Methods(POST)
handle("/api/rule/notification/test", JSON(TestHTTPNotification), canRunTests).Name("rule__notification_test").Methods(POST)
handle("/api/shorten", JSON(Shorten), canViewDash).Name("shorten")
handle("/s/{id}", JSON(GetShortLink), canViewDash).Name("shortlink")
handle("/api/silence/clear", JSON(SilenceClear), canSilence).Name("silence_clear")
handle("/api/silence/get", JSON(SilenceGet), canViewDash).Name("silence_get").Methods(GET)
handle("/api/silence/set", JSON(SilenceSet), canSilence).Name("silence_set")
Expand Down Expand Up @@ -406,41 +406,29 @@ func JSON(h func(miniprofiler.Timer, http.ResponseWriter, *http.Request) (interf
}

func Shorten(_ miniprofiler.Timer, w http.ResponseWriter, r *http.Request) (interface{}, error) {
u := url.URL{
Scheme: "https",
Host: "www.googleapis.com",
Path: "/urlshortener/v1/url",
}
if schedule.SystemConf.GetShortURLKey() != "" {
u.RawQuery = "key=" + schedule.SystemConf.GetShortURLKey()
}
j, err := json.Marshal(struct {
LongURL string `json:"longUrl"`
}{
r.Referer(),
})
id, err := schedule.DataAccess.Configs().ShortenLink(r.Referer())
if err != nil {
return nil, err
}
return struct {
ID string `json:"id"`
}{schedule.SystemConf.MakeLink(fmt.Sprintf("/s/%d", id), nil)}, nil
}

transport := &http.Transport{
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
}
if InternetProxy != nil {
transport.Proxy = http.ProxyURL(InternetProxy)
func GetShortLink(t miniprofiler.Timer, w http.ResponseWriter, r *http.Request) (interface{}, error) {
// on any error or bad param, just redirect to index. Otherwise 302 to stored url
vars := mux.Vars(r)
idv := vars["id"]
id, err := strconv.Atoi(idv)
targetURL := ""
if err != nil {
return Index(t, w, r)
}
c := http.Client{Transport: transport}

req, err := c.Post(u.String(), "application/json", bytes.NewBuffer(j))
targetURL, err = schedule.DataAccess.Configs().GetShortLink(id)
if err != nil {
return nil, err
return Index(t, w, r)
}
io.Copy(w, req.Body)
req.Body.Close()
http.Redirect(w, r, targetURL, 302)
return nil, nil
}

Expand Down