Skip to content

Commit

Permalink
feat: handle errors
Browse files Browse the repository at this point in the history
Signed-off-by: Carlos Alexandro Becker <caarlos0@gmail.com>
  • Loading branch information
caarlos0 committed Jul 31, 2021
1 parent 0a30098 commit 54d3554
Show file tree
Hide file tree
Showing 7 changed files with 48 additions and 39 deletions.
20 changes: 12 additions & 8 deletions controller/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,26 @@ package controller

import (
"html/template"
"io"
"io/fs"
"net/http"

"github.com/caarlos0/httperr"
)

func Index(fsys fs.FS) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := template.Must(template.ParseFS(fsys, "static/templates/index.html")).
Execute(w, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func Index(fsys fs.FS) http.Handler {
return httperr.NewF(func(w http.ResponseWriter, r *http.Request) error {
return executeTemplate(fsys, w, nil)
})
}

func HandleForm(fsys fs.FS) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/"+r.FormValue("repository"), http.StatusSeeOther)
}
}

func executeTemplate(fsys fs.FS, w io.Writer, data interface{}) error {
return template.Must(template.ParseFS(fsys, "static/templates/index.html")).
Execute(w, data)
}
39 changes: 16 additions & 23 deletions controller/repositories.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package controller

import (
"errors"
"fmt"
"html/template"
"io/fs"
"net/http"
"time"

"github.com/apex/log"
"github.com/caarlos0/httperr"
"github.com/caarlos0/starcharts/internal/cache"
"github.com/caarlos0/starcharts/internal/github"
"github.com/gorilla/mux"
Expand All @@ -17,24 +16,21 @@ import (
)

// GetRepo shows the given repo chart.
func GetRepo(fsys fs.FS, github *github.GitHub, cache *cache.Redis) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
func GetRepo(fsys fs.FS, github *github.GitHub, cache *cache.Redis) http.Handler {
return httperr.NewF(func(w http.ResponseWriter, r *http.Request) error {
name := fmt.Sprintf(
"%s/%s",
mux.Vars(r)["owner"],
mux.Vars(r)["repo"],
)
details, err := github.RepoDetails(r.Context(), name)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
return executeTemplate(fsys, w, map[string]error{
"Error": err,
})
}
err = template.Must(template.ParseFS(fsys, "static/templates/index.html")).
Execute(w, details)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
return executeTemplate(fsys, w, details)
})
}

// IntValueFormatter is a ValueFormatter for int.
Expand All @@ -46,8 +42,8 @@ func IntValueFormatter(v interface{}) string {
//
// nolint: funlen
// TODO: refactor.
func GetRepoChart(gh *github.GitHub, cache *cache.Redis) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
func GetRepoChart(gh *github.GitHub, cache *cache.Redis) http.Handler {
return httperr.NewF(func(w http.ResponseWriter, r *http.Request) error {
name := fmt.Sprintf(
"%s/%s",
mux.Vars(r)["owner"],
Expand All @@ -57,8 +53,7 @@ func GetRepoChart(gh *github.GitHub, cache *cache.Redis) http.HandlerFunc {
defer log.Trace("collect_stars").Stop(nil)
repo, err := gh.RepoDetails(r.Context(), name)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
return httperr.Wrap(err, http.StatusBadRequest)
}

w.Header().Add("content-type", "image/svg+xml;charset=utf-8")
Expand All @@ -67,14 +62,10 @@ func GetRepoChart(gh *github.GitHub, cache *cache.Redis) http.HandlerFunc {
w.Header().Add("expires", time.Now().Format(time.RFC1123))

stargazers, err := gh.Stargazers(r.Context(), repo)
if errors.Is(err, github.ErrTooManyStars) {
_, _ = w.Write([]byte(errSvg(err)))
return
}
if err != nil {
log.WithError(err).Error("failed to get stars")
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
_, err = w.Write([]byte(errSvg(err)))
return err
}
series := chart.TimeSeries{
Style: chart.Style{
Expand Down Expand Up @@ -133,8 +124,10 @@ func GetRepoChart(gh *github.GitHub, cache *cache.Redis) http.HandlerFunc {
defer log.Trace("chart").Stop(&err)
if err := graph.Render(chart.SVG, w); err != nil {
log.WithError(err).Error("failed to render graph")
return err
}
}
return nil
})
}

func errSvg(err error) string {
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ require (
github.com/apex/log v1.9.0
github.com/blend/go-sdk v1.1.1 // indirect
github.com/caarlos0/env/v6 v6.6.2
github.com/caarlos0/httperr v1.1.0
github.com/go-redis/cache v6.4.0+incompatible
github.com/go-redis/redis v6.15.9+incompatible
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ github.com/blend/go-sdk v1.1.1 h1:R7PcwuIxYvrGc/r9TLLfMpajIboTjqs/HyQouzgJ7mQ=
github.com/blend/go-sdk v1.1.1/go.mod h1:IP1XHXFveOXHRnojRJO7XvqWGqyzevtXND9AdSztAe8=
github.com/caarlos0/env/v6 v6.6.2 h1:BypLXDWQTA32rS4UM7pBz+/0BOuvs6C7LSeQAxMwyvI=
github.com/caarlos0/env/v6 v6.6.2/go.mod h1:P0BVSgU9zfkxfSpFUs6KsO3uWR4k3Ac0P66ibAGTybM=
github.com/caarlos0/httperr v1.1.0 h1:bvzM4cmFFd5IX6IowjjDvyvB3n2ARRlCwjwZsfVEY7E=
github.com/caarlos0/httperr v1.1.0/go.mod h1:eN09jvBHHXvCHUGwBDm3rcgNqdqmBXvcsZvSn0cWAFo=
github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ=
github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
Expand Down
8 changes: 4 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func main() {
r := mux.NewRouter()
r.Path("/").
Methods(http.MethodGet).
HandlerFunc(controller.Index(static))
Handler(controller.Index(static))
r.Path("/").
Methods(http.MethodPost).
HandlerFunc(controller.HandleForm(static))
Expand All @@ -49,10 +49,10 @@ func main() {
Handler(http.FileServer(http.FS(static)))
r.Path("/{owner}/{repo}.svg").
Methods(http.MethodGet).
HandlerFunc(controller.GetRepoChart(github, cache))
Handler(controller.GetRepoChart(github, cache))
r.Path("/{owner}/{repo}").
Methods(http.MethodGet).
HandlerFunc(controller.GetRepo(static, github, cache))
Handler(controller.GetRepo(static, github, cache))

// generic metrics
requestCounter := promauto.NewCounterVec(prometheus.CounterOpts{
Expand Down Expand Up @@ -80,7 +80,7 @@ func main() {
),
),
),
Addr: "0.0.0.0:" + config.Port,
Addr: "127.0.0.1:" + config.Port,
WriteTimeout: 30 * time.Second,
ReadTimeout: 30 * time.Second,
}
Expand Down
13 changes: 10 additions & 3 deletions static/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ div.code {
border-top: 1px solid #eee;
}

div.main>form>input[type=text] {
div.main>form>input[type=text] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
Expand All @@ -107,7 +107,7 @@ div.main>form>input[type=text] {
color: #555;
}

div.main>form>input[type=submit] {
div.main>form>input[type=submit] {
width: 100%;
background-color: #3F3D56;
color: white;
Expand All @@ -119,4 +119,11 @@ div.main>form>input[type=submit] {
font-family: inherit;
font-size: 1rem;
font-weight: 450;
}
}

p.error {
color: #e76060;
font-weight: bold;
margin-top: 1em;
margin-bottom: 1em;
}
4 changes: 3 additions & 1 deletion static/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,11 @@
{{ end }}
{{ else }}
<div class="main">
{{ with .Error }}<p class="error">{{ . }}</p>{{ end }}
<form method="POST">
<label for="repo">Repository:</label><br>
<input type="text" id="repository" name="repository" placeholder="caarlos0/starcharts"><br><br>
<input type="text" id="repository" name="repository" value="caarlos0/starcharts" placeholder="caarlos0/starcharts"
autofocus="true"><br>
<input type="submit" value="Submit">
</form>
</div>
Expand Down

0 comments on commit 54d3554

Please sign in to comment.