Allow internal server error using panic()

This commit is contained in:
Daan Sprenkels 2019-10-15 23:19:45 +02:00
parent 0ecdaafe2f
commit e193183f86
7 changed files with 43 additions and 22 deletions

View File

@ -9,12 +9,12 @@ the command line.
## USAGE ## USAGE
# Upload a file # Upload a file
curl -F'file=@yourfile.png' <a href="{{Request.Host}}">{{Request.Host}}</a> curl -F'file=@yourfile.png' <a href="{{.Request.Host}}">{{.Request.Host}}</a>
# Shorten a URL # Shorten a URL
curl -F'shorten=http://example.com/some/long/url' <a href="{{Request.Host}}">{{Request.Host}}</a> curl -F'shorten=http://example.com/some/long/url' <a href="{{.Request.Host}}">{{.Request.Host}}</a>
# Shorten a URL with a token to delete it later # Shorten a URL with a token to delete it later
curl -F'shorten=http://example.com/some/long/url' -F'deleteToken=' <a href="{{Request.Host}}">{{Request.Host}}</a> curl -F'shorten=http://example.com/some/long/url' -F'deleteToken=' <a href="{{.Request.Host}}">{{.Request.Host}}</a>
</pre> </pre>
{{end}} {{end}}

View File

@ -7,10 +7,10 @@ the command line.
## USAGE ## USAGE
# Upload a file # Upload a file
curl -F'file=@yourfile.png' {{Request.Host}} curl -F'file=@yourfile.png' {{.Request.Host}}
# Shorten a URL # Shorten a URL
curl -F'shorten=http://example.com/some/long/url' {{Request.Host}} curl -F'shorten=http://example.com/some/long/url' {{.Request.Host}}
# Shorten a URL with a token to delete it later # Shorten a URL with a token to delete it later
curl -F'shorten=http://example.com/some/long/url' -F'deleteToken=' {{Request.Host}} curl -F'shorten=http://example.com/some/long/url' -F'deleteToken=' {{.Request.Host}}

1
go.mod
View File

@ -4,6 +4,7 @@ go 1.12
require ( require (
github.com/go-bindata/go-bindata v3.1.2+incompatible // indirect github.com/go-bindata/go-bindata v3.1.2+incompatible // indirect
github.com/gorilla/handlers v1.4.2
github.com/gorilla/mux v1.7.3 github.com/gorilla/mux v1.7.3
github.com/pkg/errors v0.8.1 github.com/pkg/errors v0.8.1
github.com/prometheus/client_golang v1.1.0 github.com/prometheus/client_golang v1.1.0

2
go.sum
View File

@ -18,6 +18,8 @@ github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gorilla/handlers v1.4.2 h1:0QniY0USkHQ1RGCLfKxeNHK9bkDHGRYGNDFBCS+YARg=
github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ=
github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw= github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw=
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=

View File

@ -84,8 +84,7 @@ func viewPasteHandlerInner(w http.ResponseWriter, r *http.Request, flags viewPas
p, err = getPaste(tx, key) p, err = getPaste(tx, key)
return err return err
}); err != nil { }); err != nil {
log.Printf("error: %v\n", err) panic(err)
renderInternalServerError(w, r, err)
return return
} }
if p == nil { if p == nil {
@ -124,9 +123,7 @@ func viewPasteHandlerInner(w http.ResponseWriter, r *http.Request, flags viewPas
rawurl := string(p.Content) rawurl := string(p.Content)
urlParse, err := url.Parse(rawurl) urlParse, err := url.Parse(rawurl)
if err != nil { if err != nil {
log.Printf("error: invalid URL ('%v') in database for key '%v': %v\n", rawurl, p.Key, err) panic(errors.Wrapf(err, "invalid URL ('%v') in database for key '%v'", rawurl, p.Key))
renderInternalServerError(w, r, "invalid url in database")
return
} }
http.Redirect(w, r, urlParse.String(), http.StatusSeeOther) http.Redirect(w, r, urlParse.String(), http.StatusSeeOther)
} }
@ -134,17 +131,13 @@ func viewPasteHandlerInner(w http.ResponseWriter, r *http.Request, flags viewPas
case stateDeleted: case stateDeleted:
renderError(w, r, http.StatusGone, "paste has been deleted") renderError(w, r, http.StatusGone, "paste has been deleted")
default: default:
log.Printf("error: invalid paste.State (%v) for key '%v'\n", p.State, p.Key) panic(errors.Errorf("invalid paste.State (%v) for key '%v'", p.State, p.Key))
msg := fmt.Sprintf("internal server error: invalid paste.State (%v\n)", p.State)
renderInternalServerError(w, r, msg)
} }
} }
func newPasteHandler(w http.ResponseWriter, r *http.Request) { func newPasteHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(50 * 1000 * 1000); err != nil { if err := r.ParseMultipartForm(50 * 1000 * 1000); err != nil {
log.Printf("error: %v\n", err) panic(err)
renderInternalServerError(w, r, err)
return
} }
// Determine what kind of post this is, currently only `shorten=...` // Determine what kind of post this is, currently only `shorten=...`
@ -189,9 +182,7 @@ func newRedirectPasteHandler(w http.ResponseWriter, r *http.Request) {
paste, err = shortenURL(tx, userURL) paste, err = shortenURL(tx, userURL)
return err return err
}); err != nil { }); err != nil {
log.Printf("error: %v\n", err) panic(err)
renderInternalServerError(w, r, err)
return
} }
data := map[string]interface{}{"Paste": paste} data := map[string]interface{}{"Paste": paste}
render(w, r, "newRedirectPasteSuccess", data) render(w, r, "newRedirectPasteSuccess", data)

View File

@ -1,6 +1,7 @@
package handlers package handlers
import ( import (
"fmt"
"log" "log"
"net/http" "net/http"
"time" "time"
@ -8,9 +9,29 @@ import (
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
func recoveryMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
defer func() {
if err := recover(); err != nil {
log.Printf("error: panic while recovering from another panic: %v\n", err)
fmt.Fprintf(w, "internal server error: %v\n", err)
}
}()
if err := recover(); err != nil {
log.Printf("error: %v\n", err)
renderInternalServerError(w, r, err)
}
}()
next.ServeHTTP(w, r)
})
}
func StartMainServer() { func StartMainServer() {
// Initialize Gorilla router // Initialize Gorilla router
router := mux.NewRouter() router := mux.NewRouter()
router.Use(recoveryMiddleware)
router.HandleFunc("/", indexGetHandler).Methods("GET") router.HandleFunc("/", indexGetHandler).Methods("GET")
router.HandleFunc("/", newPasteHandler).Methods("POST") router.HandleFunc("/", newPasteHandler).Methods("POST")
router.HandleFunc("/{key:[A-Za-z0-9-_]{4,}}", viewPasteHandler).Methods("GET") router.HandleFunc("/{key:[A-Za-z0-9-_]{4,}}", viewPasteHandler).Methods("GET")

View File

@ -40,14 +40,20 @@ func init() {
for _, tmplPath := range AssetNames() { for _, tmplPath := range AssetNames() {
if mustMatch("templates/txt/*.txt.tmpl", tmplPath) { if mustMatch("templates/txt/*.txt.tmpl", tmplPath) {
base := text.Must(textBaseTemplate.Clone()) base := text.Must(textBaseTemplate.Clone())
tmpl := text.Must(base.Parse(string(MustAsset(tmplPath)))) tmpl, err := base.Parse(string(MustAsset(tmplPath)))
if err != nil {
panic(errors.Wrapf(err, "parsing %v", tmplPath))
}
tmplName := strings.TrimSuffix(filepath.Base(tmplPath), ".txt.tmpl") tmplName := strings.TrimSuffix(filepath.Base(tmplPath), ".txt.tmpl")
textTemplates[tmplName] = tmpl textTemplates[tmplName] = tmpl
continue continue
} }
if mustMatch("templates/html/*.html.tmpl", tmplPath) { if mustMatch("templates/html/*.html.tmpl", tmplPath) {
base := html.Must(htmlBaseTemplate.Clone()) base := html.Must(htmlBaseTemplate.Clone())
tmpl := html.Must(base.Parse(string(MustAsset(tmplPath)))) tmpl, err := base.Parse(string(MustAsset(tmplPath)))
if err != nil {
panic(errors.Wrapf(err, "parsing %v", tmplPath))
}
tmplName := strings.TrimSuffix(filepath.Base(tmplPath), ".html.tmpl") tmplName := strings.TrimSuffix(filepath.Base(tmplPath), ".html.tmpl")
htmlTemplates[tmplName] = tmpl htmlTemplates[tmplName] = tmpl
continue continue