mirror of
https://github.com/taigrr/shorturl
synced 2025-01-18 04:03:16 -08:00
Refactored. New UI Design
This commit is contained in:
parent
d4b2e6eac8
commit
74c02644c5
@ -14,4 +14,6 @@ WORKDIR /go/src/shorturl
|
||||
COPY . /go/src/shorturl
|
||||
|
||||
RUN go get -v -d
|
||||
RUN go get github.com/GeertJohan/go.rice/rice
|
||||
RUN rice embed-go
|
||||
RUN go install -v
|
||||
|
6
config.go
Normal file
6
config.go
Normal file
@ -0,0 +1,6 @@
|
||||
package main
|
||||
|
||||
// Config ...
|
||||
type Config struct {
|
||||
baseURL string
|
||||
}
|
22
config_test.go
Normal file
22
config_test.go
Normal file
@ -0,0 +1,22 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestZeroConfig(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
cfg := Config{}
|
||||
assert.Equal(cfg.baseURL, "")
|
||||
}
|
||||
|
||||
func TestConfig(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
cfg := Config{baseURL: "http://localhost:8000/"}
|
||||
assert.Equal(cfg.baseURL, "http://localhost:8000/")
|
||||
}
|
16
main.go
16
main.go
@ -8,18 +8,21 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
db *bolt.DB
|
||||
cfg Config
|
||||
db *bolt.DB
|
||||
)
|
||||
|
||||
func main() {
|
||||
var (
|
||||
config string
|
||||
dbpath string
|
||||
bind string
|
||||
config string
|
||||
dbpath string
|
||||
baseurl string
|
||||
bind string
|
||||
)
|
||||
|
||||
flag.StringVar(&config, "config", "", "config file")
|
||||
flag.StringVar(&dbpath, "dbpath", "urls.db", "Database path")
|
||||
flag.StringVar(&baseurl, "baseurl", "", "Base URL for display purposes")
|
||||
flag.StringVar(&bind, "bind", "0.0.0.0:8000", "[int]:<port> to bind to")
|
||||
flag.Parse()
|
||||
|
||||
@ -30,5 +33,8 @@ func main() {
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
NewServer(bind).ListenAndServe()
|
||||
// TODO: Abstract the Config and Handlers better
|
||||
cfg.baseURL = baseurl
|
||||
|
||||
NewServer(bind, cfg).ListenAndServe()
|
||||
}
|
||||
|
181
server.go
181
server.go
@ -1,23 +1,75 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
// Logging
|
||||
"github.com/unrolled/logger"
|
||||
|
||||
// Stats/Metrics
|
||||
"github.com/rcrowley/go-metrics"
|
||||
"github.com/rcrowley/go-metrics/exp"
|
||||
"github.com/thoas/stats"
|
||||
|
||||
"github.com/GeertJohan/go.rice"
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"go.iondynamics.net/templice"
|
||||
)
|
||||
|
||||
// Counters ...
|
||||
type Counters struct {
|
||||
r metrics.Registry
|
||||
}
|
||||
|
||||
func NewCounters() *Counters {
|
||||
counters := &Counters{
|
||||
r: metrics.NewRegistry(),
|
||||
}
|
||||
return counters
|
||||
}
|
||||
|
||||
func (c *Counters) Inc(name string) {
|
||||
metrics.GetOrRegisterCounter(name, c.r).Inc(1)
|
||||
}
|
||||
|
||||
func (c *Counters) Dec(name string) {
|
||||
metrics.GetOrRegisterCounter(name, c.r).Dec(1)
|
||||
}
|
||||
|
||||
func (c *Counters) IncBy(name string, n int64) {
|
||||
metrics.GetOrRegisterCounter(name, c.r).Inc(n)
|
||||
}
|
||||
|
||||
func (c *Counters) DecBy(name string, n int64) {
|
||||
metrics.GetOrRegisterCounter(name, c.r).Dec(n)
|
||||
}
|
||||
|
||||
// Server ...
|
||||
type Server struct {
|
||||
bind string
|
||||
templates *templice.Template
|
||||
config Config
|
||||
templates *Templates
|
||||
router *httprouter.Router
|
||||
|
||||
// Logger
|
||||
logger *logger.Logger
|
||||
|
||||
// Stats/Metrics
|
||||
counters *Counters
|
||||
stats *stats.Stats
|
||||
}
|
||||
|
||||
func (s *Server) render(w http.ResponseWriter, tmpl string, data interface{}) {
|
||||
err := s.templates.ExecuteTemplate(w, tmpl+".html", data)
|
||||
func (s *Server) render(name string, w http.ResponseWriter, ctx interface{}) {
|
||||
buf, err := s.templates.Exec(name, ctx)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
_, err = buf.WriteTo(w)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
@ -26,33 +78,79 @@ func (s *Server) render(w http.ResponseWriter, tmpl string, data interface{}) {
|
||||
// IndexHandler ...
|
||||
func (s *Server) IndexHandler() httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
s.render(w, "index", nil)
|
||||
s.counters.Inc("n_index")
|
||||
|
||||
s.render("index", w, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// ShortenHandler ...
|
||||
func (s *Server) ShortenHandler() httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||
err := r.ParseForm()
|
||||
s.counters.Inc("n_shorten")
|
||||
|
||||
u, err := NewURL(r.FormValue("url"))
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
url := r.Form.Get("url")
|
||||
u, err := NewURL(url)
|
||||
redirectURL, err := url.Parse(fmt.Sprintf("./u/%s", u.ID()))
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Error", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
http.Redirect(w, r, redirectURL.String(), http.StatusFound)
|
||||
}
|
||||
}
|
||||
|
||||
// ViewHandler ...
|
||||
func (s *Server) ViewHandler() httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||
s.counters.Inc("n_view")
|
||||
|
||||
id := p.ByName("id")
|
||||
if id == "" {
|
||||
http.Error(w, "Bad Request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
s.render(w, "url", struct{ ID string }{ID: u.ID()})
|
||||
u, ok := LookupURL(id)
|
||||
if !ok {
|
||||
http.Error(w, "Not Found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
baseURL, err := url.Parse(s.config.baseURL)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Error", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
redirectURL, err := url.Parse(fmt.Sprintf("./r/%s", u.ID()))
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Error", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
fullURL := baseURL.ResolveReference(redirectURL)
|
||||
|
||||
s.render(
|
||||
"view", w,
|
||||
struct {
|
||||
ID string
|
||||
URL string
|
||||
}{
|
||||
ID: u.ID(),
|
||||
URL: fullURL.String(),
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// RedirectHandler ...
|
||||
func (s *Server) RedirectHandler() httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||
s.counters.Inc("n_redirect")
|
||||
|
||||
id := p.ByName("id")
|
||||
if id == "" {
|
||||
http.Error(w, "Bad Request", http.StatusBadRequest)
|
||||
@ -69,29 +167,78 @@ func (s *Server) RedirectHandler() httprouter.Handle {
|
||||
}
|
||||
}
|
||||
|
||||
// StatsHandler ...
|
||||
func (s *Server) StatsHandler() httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
bs, err := json.Marshal(s.stats.Data())
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
w.Write(bs)
|
||||
}
|
||||
}
|
||||
|
||||
// ListenAndServe ...
|
||||
func (s *Server) ListenAndServe() {
|
||||
log.Fatal(http.ListenAndServe(s.bind, s.router))
|
||||
log.Fatal(
|
||||
http.ListenAndServe(
|
||||
s.bind,
|
||||
s.logger.Handler(
|
||||
s.stats.Handler(s.router),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
func (s *Server) initRoutes() {
|
||||
s.router.Handler("GET", "/debug/metrics", exp.ExpHandler(s.counters.r))
|
||||
s.router.GET("/debug/stats", s.StatsHandler())
|
||||
|
||||
s.router.ServeFiles(
|
||||
"/css/*filepath",
|
||||
rice.MustFindBox("static/css").HTTPBox(),
|
||||
)
|
||||
|
||||
s.router.GET("/", s.IndexHandler())
|
||||
s.router.POST("/", s.ShortenHandler())
|
||||
s.router.GET("/:id", s.RedirectHandler())
|
||||
s.router.GET("/u/:id", s.ViewHandler())
|
||||
s.router.GET("/r/:id", s.RedirectHandler())
|
||||
}
|
||||
|
||||
// NewServer ...
|
||||
func NewServer(bind string) *Server {
|
||||
func NewServer(bind string, config Config) *Server {
|
||||
server := &Server{
|
||||
bind: bind,
|
||||
config: config,
|
||||
router: httprouter.New(),
|
||||
templates: templice.New(rice.MustFindBox("templates")),
|
||||
templates: NewTemplates("base"),
|
||||
|
||||
// Logger
|
||||
logger: logger.New(logger.Options{
|
||||
Prefix: "shorturl",
|
||||
RemoteAddressHeaders: []string{"X-Forwarded-For"},
|
||||
OutputFlags: log.LstdFlags,
|
||||
}),
|
||||
|
||||
// Stats/Metrics
|
||||
counters: NewCounters(),
|
||||
stats: stats.New(),
|
||||
}
|
||||
|
||||
err := server.templates.Load()
|
||||
if err != nil {
|
||||
log.Panicf("error loading templates: %s", err)
|
||||
}
|
||||
// Templates
|
||||
box := rice.MustFindBox("templates")
|
||||
|
||||
indexTemplate := template.New("index")
|
||||
template.Must(indexTemplate.Parse(box.MustString("index.html")))
|
||||
template.Must(indexTemplate.Parse(box.MustString("base.html")))
|
||||
|
||||
viewTemplate := template.New("view")
|
||||
template.Must(viewTemplate.Parse(box.MustString("view.html")))
|
||||
template.Must(viewTemplate.Parse(box.MustString("base.html")))
|
||||
|
||||
server.templates.Add("index", indexTemplate)
|
||||
server.templates.Add("view", viewTemplate)
|
||||
|
||||
server.initRoutes()
|
||||
|
||||
|
1
static/css/spectre-icons.min.css
vendored
Normal file
1
static/css/spectre-icons.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
static/css/spectre.min.css
vendored
Normal file
1
static/css/spectre.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
53
templates.go
Normal file
53
templates.go
Normal file
@ -0,0 +1,53 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"log"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type TemplateMap map[string]*template.Template
|
||||
|
||||
type Templates struct {
|
||||
sync.Mutex
|
||||
|
||||
base string
|
||||
templates TemplateMap
|
||||
}
|
||||
|
||||
func NewTemplates(base string) *Templates {
|
||||
return &Templates{
|
||||
base: base,
|
||||
templates: make(TemplateMap),
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Templates) Add(name string, template *template.Template) {
|
||||
t.Lock()
|
||||
defer t.Unlock()
|
||||
|
||||
t.templates[name] = template
|
||||
}
|
||||
|
||||
func (t *Templates) Exec(name string, ctx interface{}) (io.WriterTo, error) {
|
||||
t.Lock()
|
||||
defer t.Unlock()
|
||||
|
||||
template, ok := t.templates[name]
|
||||
if !ok {
|
||||
log.Printf("template %s not found", name)
|
||||
return nil, fmt.Errorf("no such template: %s", name)
|
||||
}
|
||||
|
||||
buf := bytes.NewBuffer([]byte{})
|
||||
err := template.ExecuteTemplate(buf, t.base, ctx)
|
||||
if err != nil {
|
||||
log.Printf("error parsing template %s: %s", name, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return buf, nil
|
||||
}
|
22
templates/base.html
Normal file
22
templates/base.html
Normal file
@ -0,0 +1,22 @@
|
||||
{{define "base"}}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<link rel="stylesheet" href="/css/spectre-icons.min.css">
|
||||
<link rel="stylesheet" href="/css/spectre.min.css">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>ShortURL</title>
|
||||
</head>
|
||||
<body>
|
||||
<section class="container grid-960 mt-10">
|
||||
<header class="navbar">
|
||||
<section class="navbar-section">
|
||||
<a href="/" class="navbar-brand mr-10">ShortURL</a>
|
||||
</section>
|
||||
<section class="navbar-section"></section>
|
||||
</header>
|
||||
{{template "content" .}}
|
||||
</section>
|
||||
</body>
|
||||
</html>
|
||||
{{end}}
|
@ -1,14 +1,17 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>shorturl</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<p>Enter your long URL here:</p>
|
||||
<form method="POST" action="">
|
||||
<input type="text" name="url">
|
||||
<input type="submit">
|
||||
</form>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
{{define "content"}}
|
||||
<section class="container">
|
||||
<div class="columns">
|
||||
<div class="column">
|
||||
<form action="" method="POST">
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="input-url"></label>
|
||||
<input class="form-input" id="input-url" type="text" name="url" placeholder="Enter long url here...">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<button class="btn btn-sm btn-primary" type="submit">Shorten</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{{end}}
|
||||
|
@ -1,10 +0,0 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>shorturl</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<p>Your short url is: <a href="/{{.ID}}">{{.ID}}</a></p>
|
||||
</body>
|
||||
|
||||
</html>
|
10
templates/view.html
Normal file
10
templates/view.html
Normal file
@ -0,0 +1,10 @@
|
||||
{{define "content"}}
|
||||
<section class="container">
|
||||
<div class="columns">
|
||||
<div class="column">
|
||||
<p>Your short url is: <a href="/r/{{.ID}}">{{.ID}}</a></p>
|
||||
<code>{{.URL}}</code>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{{end}}
|
Loading…
x
Reference in New Issue
Block a user