Revert "Format errors with HTML"
This reverts commit 80092dea5b
.
After enabling both HTML and plain-text templating, I found that
this introduces a lot more complexity in the code than was desirable
for a project in this stage. The result looked fine, wrapping plain
text in <pre> tags. However, it was neccessary to keep duplicate
template files, for HTML and text. This was cumbersome, added a lot
of bloat, etc.
This feature is postponed to when there is more product.
This commit is contained in:
parent
80092dea5b
commit
675245722f
@ -1,8 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8">
|
|
||||||
<title>{{.Title}} | rushlink</title>
|
|
||||||
</head>
|
|
||||||
<pre>
|
|
||||||
{{.Content}}
|
|
||||||
</pre>
|
|
2
go.mod
2
go.mod
@ -5,6 +5,8 @@ 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/mux v1.7.3
|
github.com/gorilla/mux v1.7.3
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
|
github.com/modern-go/reflect2 v1.0.1 // indirect
|
||||||
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
|
||||||
go.etcd.io/bbolt v1.3.3
|
go.etcd.io/bbolt v1.3.3
|
||||||
|
6
go.sum
6
go.sum
@ -6,6 +6,7 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
|||||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/go-bindata/go-bindata v3.1.2+incompatible h1:5vjJMVhowQdPzjE1LdxyFF7YFTXg5IgGVW4gBr5IbvE=
|
||||||
github.com/go-bindata/go-bindata v3.1.2+incompatible/go.mod h1:xK8Dsgwmeed+BBsSy2XTopBn/8uK2HWuGSnA11C3Joo=
|
github.com/go-bindata/go-bindata v3.1.2+incompatible/go.mod h1:xK8Dsgwmeed+BBsSy2XTopBn/8uK2HWuGSnA11C3Joo=
|
||||||
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||||
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
||||||
@ -18,7 +19,10 @@ 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/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/joomcode/errorx v1.0.0 h1:RJAKLTy1Sv2Tszhu14m5RZP4VGRlhXutG/XlL1En5VM=
|
||||||
|
github.com/joomcode/errorx v1.0.0/go.mod h1:kgco15ekB6cs+4Xjzo7SPeXzx38PbJzBwbnu9qfVNHQ=
|
||||||
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
|
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
|
||||||
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||||
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
|
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
|
||||||
@ -32,6 +36,7 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN
|
|||||||
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||||
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||||
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
|
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
|
||||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
||||||
@ -53,6 +58,7 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
|
|||||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
go.etcd.io/bbolt v1.3.3 h1:MUGmc65QhB3pIlaQ5bB4LwqSj6GIonVJXpZiaKNyaKk=
|
||||||
go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
|
go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
|
||||||
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
240
handlers.go
240
handlers.go
@ -10,15 +10,10 @@ import (
|
|||||||
"crypto/subtle"
|
"crypto/subtle"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
"html/template"
|
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"regexp"
|
|
||||||
"runtime/debug"
|
|
||||||
"sort"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
"unicode"
|
"unicode"
|
||||||
@ -41,11 +36,6 @@ type StoredPaste struct {
|
|||||||
TimeCreated time.Time
|
TimeCreated time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTMLPage struct {
|
|
||||||
Title string
|
|
||||||
Content string
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
const (
|
||||||
TypePaste PasteType = iota
|
TypePaste PasteType = iota
|
||||||
TypeRedirect
|
TypeRedirect
|
||||||
@ -65,16 +55,8 @@ var ReservedPasteKeys [][]byte = [][]byte{[]byte("xd42"), []byte("example")}
|
|||||||
var base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
|
var base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
|
||||||
var base64Encoder = base64.NewEncoding(base64Alphabet).WithPadding(base64.NoPadding)
|
var base64Encoder = base64.NewEncoding(base64Alphabet).WithPadding(base64.NoPadding)
|
||||||
|
|
||||||
// Asset contents
|
// Page contents
|
||||||
var layoutContents = string(MustAsset("assets/layout.html"))
|
var indexContents = MustAsset("assets/index.txt")
|
||||||
var indexContents = string(MustAsset("assets/index.txt"))
|
|
||||||
|
|
||||||
// Templates
|
|
||||||
var HtmlTemplate = template.Must(template.New("layout").Parse(layoutContents))
|
|
||||||
|
|
||||||
var acceptHeaderMediaRangeRegex = regexp.MustCompile(`^\s*([^()<>@,;:\\"/\[\]?.=]+)/([^()<>@,;:\\"/\[\]?.=]+)\s*$`)
|
|
||||||
var acceptHeaderAcceptParamsRegex = regexp.MustCompile(`^\s*(\w+)=([A-Za-z0-9.-])\s*$`)
|
|
||||||
var acceptHeaderWeight = regexp.MustCompile(`^\s*q=0(?:\.([0-9]{0,3}))|1(?:\.0{0,3})\s*$`)
|
|
||||||
|
|
||||||
func (t PasteType) String() (string, error) {
|
func (t PasteType) String() (string, error) {
|
||||||
switch t {
|
switch t {
|
||||||
@ -99,30 +81,36 @@ func (t PasteState) String() (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func indexGetHandler(w http.ResponseWriter, r *http.Request) {
|
func indexGetHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
page := HTMLPage{Title: "rushlink", Content: indexContents}
|
_, err := w.Write(indexContents)
|
||||||
RenderPage(w, r, page)
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func indexPostHandler(w http.ResponseWriter, r *http.Request) {
|
func indexPostHandler(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)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
msg := fmt.Sprintf("internal server error: %v\n", err)
|
fmt.Fprintf(w, "Internal server error: %v\n", err)
|
||||||
RenderError(w, r, http.StatusInternalServerError, msg)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine what kind of post this is, currently only `shorten=...`
|
// Determine what kind of post this is, currently only `shorten=...`
|
||||||
if len(r.PostForm) == 0 {
|
if len(r.PostForm) == 0 {
|
||||||
RenderError(w, r, http.StatusBadRequest, "empty body in POST request\n")
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
var buf []byte
|
||||||
|
r.Body.Read(buf)
|
||||||
|
io.WriteString(w, "empty body in POST request\n")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
shorten_values, prs := r.PostForm["shorten"]
|
shorten_values, prs := r.PostForm["shorten"]
|
||||||
if !prs {
|
if !prs {
|
||||||
RenderError(w, r, http.StatusBadRequest, "no 'shorten' param supplied\n")
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
io.WriteString(w, "no 'shorten' param supplied\n")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if len(shorten_values) != 1 {
|
if len(shorten_values) != 1 {
|
||||||
RenderError(w, r, http.StatusBadRequest, "only one 'shorten' param is allowed per request\n")
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
io.WriteString(w, "only one 'shorten' param is allowed per request\n")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -150,29 +138,30 @@ func pasteGetHandlerInner(w http.ResponseWriter, r *http.Request, noRedirect, sh
|
|||||||
storedPaste, err = getURL(tx, []byte(key))
|
storedPaste, err = getURL(tx, []byte(key))
|
||||||
return err
|
return err
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
log.Printf("error: %v\n", err)
|
log.Printf("error: %v\n", err)
|
||||||
msg := fmt.Sprintf("internal server error: %v\n", err)
|
fmt.Fprintf(w, "internal server error: %v\n", err)
|
||||||
RenderError(w, r, http.StatusInternalServerError, msg)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if storedPaste == nil {
|
if storedPaste == nil {
|
||||||
RenderError(w, r, http.StatusNotFound, "url key not found in the database\n")
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
fmt.Fprintf(w, "url key not found in the database\n")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if showMeta {
|
if showMeta {
|
||||||
typeString, err := storedPaste.Type.String()
|
typeString, err := storedPaste.Type.String()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
log.Printf("error: %v\n", err)
|
log.Printf("error: %v\n", err)
|
||||||
msg := fmt.Sprintf("internal server error: %v\n", err)
|
fmt.Fprintf(w, "internal server error: %v\n", err)
|
||||||
RenderError(w, r, http.StatusInternalServerError, msg)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
stateString, err := storedPaste.State.String()
|
stateString, err := storedPaste.State.String()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
log.Printf("error: %v\n", err)
|
log.Printf("error: %v\n", err)
|
||||||
msg := fmt.Sprintf("internal server error: %v\n", err)
|
fmt.Fprintf(w, "internal server error: %v\n", err)
|
||||||
RenderError(w, r, http.StatusInternalServerError, msg)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
isOwner := "no"
|
isOwner := "no"
|
||||||
@ -196,23 +185,21 @@ func pasteGetHandlerInner(w http.ResponseWriter, r *http.Request, noRedirect, sh
|
|||||||
rawurl := string(storedPaste.Content)
|
rawurl := string(storedPaste.Content)
|
||||||
urlParse, err := url.Parse(rawurl)
|
urlParse, err := url.Parse(rawurl)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
log.Printf("error: invalid URL ('%v') in database for key '%v': %v\n", rawurl, storedPaste.Key, err)
|
log.Printf("error: invalid URL ('%v') in database for key '%v': %v\n", rawurl, storedPaste.Key, err)
|
||||||
msg := fmt.Sprintf("internal server error: invalid url in database\n")
|
fmt.Fprintf(w, "internal server error: invalid url in database\n")
|
||||||
RenderError(w, r, http.StatusInternalServerError, msg)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
http.Redirect(w, r, urlParse.String(), http.StatusSeeOther)
|
http.Redirect(w, r, urlParse.String(), http.StatusSeeOther)
|
||||||
}
|
}
|
||||||
w.Write(storedPaste.Content)
|
w.Write(storedPaste.Content)
|
||||||
case StateDeleted:
|
case StateDeleted:
|
||||||
RenderError(w, r, http.StatusGone, "paste has been deleted\n")
|
w.WriteHeader(http.StatusGone)
|
||||||
return
|
fmt.Fprintf(w, "key has been deleted\n")
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
log.Printf("error: invalid storedPaste.State (%v) for key '%v'\n", storedPaste.State, storedPaste.Key)
|
log.Printf("error: invalid storedPaste.State (%v) for key '%v'\n", storedPaste.State, storedPaste.Key)
|
||||||
msg := fmt.Sprintf("internal server error: invalid storedPaste.State (%v)\n", storedPaste.State)
|
fmt.Fprintf(w, "internal server error: invalid storedPaste.State (%v\n)", storedPaste.State)
|
||||||
RenderError(w, r, http.StatusInternalServerError, msg)
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -220,18 +207,18 @@ func shortenPostHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
rawurl := r.PostForm.Get("shorten")
|
rawurl := r.PostForm.Get("shorten")
|
||||||
userURL, err := url.ParseRequestURI(rawurl)
|
userURL, err := url.ParseRequestURI(rawurl)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
msg := fmt.Sprintf("invalid url (%v): %v\n", err, rawurl)
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
RenderError(w, r, http.StatusBadRequest, msg)
|
fmt.Fprintf(w, "invalid url (%v): %v\n", err, rawurl)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if userURL.Scheme == "" {
|
if userURL.Scheme == "" {
|
||||||
msg := fmt.Sprintf("invalid url (unspecified scheme)\n", rawurl)
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
RenderError(w, r, http.StatusBadRequest, msg)
|
fmt.Fprintf(w, "invalid url (unspecified scheme)\n", rawurl)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if userURL.Host == "" {
|
if userURL.Host == "" {
|
||||||
msg := fmt.Sprintf("invalid url (unspecified host)\n", rawurl)
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
RenderError(w, r, http.StatusBadRequest, msg)
|
fmt.Fprintf(w, "invalid url (unspecified host)\n", rawurl)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -250,30 +237,23 @@ func shortenPostHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
storedPaste = sp
|
storedPaste = sp
|
||||||
return err
|
return err
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
log.Printf("error: %v\n", err)
|
log.Printf("error: %v\n", err)
|
||||||
msg := fmt.Sprintf("internal server error: %v\n", err)
|
fmt.Fprintf(w, "internal server error: %v\n", err)
|
||||||
RenderError(w, r, http.StatusInternalServerError, msg)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
saveURL, err := r.URL.Parse(string(storedPaste.Key))
|
saveURL, err := r.URL.Parse(string(storedPaste.Key))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = errors.Wrap(err, "parsing url")
|
log.Printf("error: %v\n", errors.Wrap(err, "parsing url"))
|
||||||
log.Printf("error: %v\n", err)
|
|
||||||
msg := fmt.Sprintf("internal server error: %v\n", err)
|
|
||||||
RenderError(w, r, http.StatusInternalServerError, msg)
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
var base64OwnerToken = make([]byte, 24)
|
var base64OwnerToken = make([]byte, 24)
|
||||||
base64Encoder.Encode(base64OwnerToken, storedPaste.OwnerToken[:])
|
base64Encoder.Encode(base64OwnerToken, storedPaste.OwnerToken[:])
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
fmt.Fprintf(w, "URL saved at %v\n", saveURL)
|
||||||
isNotPrint := func(r rune) bool { return !unicode.IsPrint(r) }
|
isNotPrint := func(r rune) bool { return !unicode.IsPrint(r) }
|
||||||
ownerKey := strings.TrimRightFunc(string(base64OwnerToken), isNotPrint)
|
fmt.Fprintf(w, "Owner key is %s\n", strings.TrimRightFunc(string(base64OwnerToken), isNotPrint))
|
||||||
page := HTMLPage{
|
|
||||||
Title: fmt.Sprintf("URL saved at %v\n", saveURL),
|
|
||||||
Content: fmt.Sprintf("URL saved at %v\nOwner key is %s\n", saveURL, ownerKey),
|
|
||||||
}
|
|
||||||
RenderPage(w, r, page)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Retrieve a URL from the database
|
// Retrieve a URL from the database
|
||||||
@ -407,141 +387,3 @@ func getOwnerTokenFromRequest(r *http.Request) ([16]byte, bool) {
|
|||||||
}
|
}
|
||||||
return ownerKey, false
|
return ownerKey, false
|
||||||
}
|
}
|
||||||
|
|
||||||
func RenderPage(w http.ResponseWriter, r *http.Request, page HTMLPage) {
|
|
||||||
contentType, err := resolveResponseContentType(r, []string{"text/plain", "text/html"})
|
|
||||||
if err != nil {
|
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
|
||||||
log.Printf("error: %v\n", err)
|
|
||||||
fmt.Fprintf(w, "internal server error: %v\n", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch contentType {
|
|
||||||
case "text/plain":
|
|
||||||
w.Header().Set("Content-Type", "text/plain")
|
|
||||||
io.WriteString(w, page.Content)
|
|
||||||
case "text/html":
|
|
||||||
w.Header().Set("Content-Type", "text/html")
|
|
||||||
err = HtmlTemplate.Execute(w, page)
|
|
||||||
default:
|
|
||||||
w.WriteHeader(http.StatusNotAcceptable)
|
|
||||||
io.WriteString(w, "could not resolve an acceptable content-type\n")
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func RenderError(w http.ResponseWriter, r *http.Request, status int, msg string) {
|
|
||||||
statusText := http.StatusText(status)
|
|
||||||
if statusText == "" {
|
|
||||||
statusText = "Unkown"
|
|
||||||
}
|
|
||||||
w.WriteHeader(status)
|
|
||||||
page := HTMLPage{
|
|
||||||
Title: fmt.Sprintf("%v %v", status, statusText),
|
|
||||||
Content: msg,
|
|
||||||
}
|
|
||||||
RenderPage(w, r, page)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to resolve the preferred content-type for the response to this request.
|
|
||||||
//
|
|
||||||
// This is done by reading from the `types` argument. If one of them matches
|
|
||||||
// the preferences supplied by the client in their Accept header, we will
|
|
||||||
// return that one. We will take the clients preferences into account.
|
|
||||||
//
|
|
||||||
// Iff no match could be found, this function will return an empty string, and
|
|
||||||
// the caller should probably respond with a 406 Not Acceptable status code.
|
|
||||||
// Iff the Accept header was invalid, we will return an error. In this case,
|
|
||||||
// the situation calls for a 400 Bad Request.
|
|
||||||
func resolveResponseContentType(r *http.Request, types []string) (string, error) {
|
|
||||||
// Ref: https://tools.ietf.org/html/rfc7231#section-5.3.2
|
|
||||||
if len(types) == 0 {
|
|
||||||
return "", nil
|
|
||||||
}
|
|
||||||
acceptHeader := r.Header.Get("Accept")
|
|
||||||
if acceptHeader == "" {
|
|
||||||
return types[0], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type AcceptValue struct {
|
|
||||||
Type string
|
|
||||||
Subtype string
|
|
||||||
Weight int
|
|
||||||
}
|
|
||||||
|
|
||||||
avStrings := strings.Split(acceptHeader, ",")
|
|
||||||
avs := make([]AcceptValue, len(avStrings))
|
|
||||||
for i, avString := range avStrings {
|
|
||||||
av := AcceptValue{Weight: 1000}
|
|
||||||
choiceParts := strings.Split(avString, ";")
|
|
||||||
mediaRange := acceptHeaderMediaRangeRegex.FindStringSubmatch(choiceParts[0])
|
|
||||||
if mediaRange == nil {
|
|
||||||
return "", fmt.Errorf("bad media-range (\"%v\")", choiceParts[0])
|
|
||||||
}
|
|
||||||
av.Type = mediaRange[1]
|
|
||||||
av.Subtype = mediaRange[2]
|
|
||||||
// Go through the rest to see if there is a q=... parameter
|
|
||||||
for choiceParts = choiceParts[1:]; len(choiceParts) > 0; choiceParts = choiceParts[1:] {
|
|
||||||
// Try to parse the weight param
|
|
||||||
weight := acceptHeaderWeight.FindStringSubmatch(choiceParts[0])
|
|
||||||
if weight != nil {
|
|
||||||
if weight[1] == "" {
|
|
||||||
av.Weight = 0
|
|
||||||
} else {
|
|
||||||
var err error
|
|
||||||
av.Weight, err = strconv.Atoi((weight[1] + "000")[:3])
|
|
||||||
if err != nil {
|
|
||||||
log.Println("error: unreachable statement")
|
|
||||||
debug.PrintStack()
|
|
||||||
av.Weight = 1000 // Reset to default value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
// Check if this parameter is still invalid in any case
|
|
||||||
acceptParams := acceptHeaderAcceptParamsRegex.FindStringSubmatchIndex(choiceParts[0])
|
|
||||||
if acceptParams == nil {
|
|
||||||
return "", fmt.Errorf("bad accept-params (\"%v\")", choiceParts[0])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
avs[i] = av
|
|
||||||
}
|
|
||||||
|
|
||||||
sort.SliceStable(avs, func(i, j int) bool {
|
|
||||||
if avs[i].Weight > avs[j].Weight {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if avs[i].Type != "*" && avs[j].Type == "*" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if avs[i].Subtype != "*" && avs[j].Subtype == "*" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
})
|
|
||||||
|
|
||||||
avArgs := make([]AcceptValue, len(types))
|
|
||||||
for i, fulltype := range types {
|
|
||||||
split := strings.Split(fulltype, "/")
|
|
||||||
if len(split) == 1 {
|
|
||||||
avArgs[i] = AcceptValue{Type: split[0]}
|
|
||||||
} else {
|
|
||||||
avArgs[i] = AcceptValue{Type: split[0], Subtype: split[1]}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, av := range avs {
|
|
||||||
for j, avArg := range avArgs {
|
|
||||||
if !(av.Type == avArg.Type || av.Type == "*" || avArg.Type == "*") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !(av.Subtype == avArg.Subtype || av.Subtype == "*" || avArg.Subtype == "*") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
return types[j], nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "", nil
|
|
||||||
}
|
|
||||||
|
Loading…
Reference in New Issue
Block a user