diff --git a/assets/layout.html b/assets/layout.html deleted file mode 100644 index 89b05ff..0000000 --- a/assets/layout.html +++ /dev/null @@ -1,8 +0,0 @@ - - - - {{.Title}} | rushlink - -
-{{.Content}}
-
\ No newline at end of file diff --git a/go.mod b/go.mod index 08f20a7..7532190 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,8 @@ go 1.12 require ( github.com/go-bindata/go-bindata v3.1.2+incompatible // indirect 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/prometheus/client_golang v1.1.0 go.etcd.io/bbolt v1.3.3 diff --git a/go.sum b/go.sum index 659278b..d31f809 100644 --- a/go.sum +++ b/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/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/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-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= 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/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/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw= 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.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= 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/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.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= 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/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/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 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= 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= diff --git a/handlers.go b/handlers.go index cf4a3eb..fdd71f0 100644 --- a/handlers.go +++ b/handlers.go @@ -10,15 +10,10 @@ import ( "crypto/subtle" "encoding/base64" "fmt" - "html/template" "io" "log" "net/http" "net/url" - "regexp" - "runtime/debug" - "sort" - "strconv" "strings" "time" "unicode" @@ -41,11 +36,6 @@ type StoredPaste struct { TimeCreated time.Time } -type HTMLPage struct { - Title string - Content string -} - const ( TypePaste PasteType = iota TypeRedirect @@ -65,16 +55,8 @@ var ReservedPasteKeys [][]byte = [][]byte{[]byte("xd42"), []byte("example")} var base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" var base64Encoder = base64.NewEncoding(base64Alphabet).WithPadding(base64.NoPadding) -// Asset contents -var layoutContents = string(MustAsset("assets/layout.html")) -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*$`) +// Page contents +var indexContents = MustAsset("assets/index.txt") func (t PasteType) String() (string, error) { switch t { @@ -99,30 +81,36 @@ func (t PasteState) String() (string, error) { } func indexGetHandler(w http.ResponseWriter, r *http.Request) { - page := HTMLPage{Title: "rushlink", Content: indexContents} - RenderPage(w, r, page) + _, err := w.Write(indexContents) + if err != nil { + panic(err) + } } func indexPostHandler(w http.ResponseWriter, r *http.Request) { if err := r.ParseMultipartForm(50 * 1000 * 1000); err != nil { - log.Printf("error: %v\n", err) - msg := fmt.Sprintf("internal server error: %v\n", err) - RenderError(w, r, http.StatusInternalServerError, msg) + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintf(w, "Internal server error: %v\n", err) return } // Determine what kind of post this is, currently only `shorten=...` 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 } shorten_values, prs := r.PostForm["shorten"] 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 } 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 } @@ -150,29 +138,30 @@ func pasteGetHandlerInner(w http.ResponseWriter, r *http.Request, noRedirect, sh storedPaste, err = getURL(tx, []byte(key)) return err }); err != nil { + w.WriteHeader(http.StatusInternalServerError) log.Printf("error: %v\n", err) - msg := fmt.Sprintf("internal server error: %v\n", err) - RenderError(w, r, http.StatusInternalServerError, msg) + fmt.Fprintf(w, "internal server error: %v\n", err) return } 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 } if showMeta { typeString, err := storedPaste.Type.String() if err != nil { + w.WriteHeader(http.StatusInternalServerError) log.Printf("error: %v\n", err) - msg := fmt.Sprintf("internal server error: %v\n", err) - RenderError(w, r, http.StatusInternalServerError, msg) + fmt.Fprintf(w, "internal server error: %v\n", err) return } stateString, err := storedPaste.State.String() if err != nil { + w.WriteHeader(http.StatusInternalServerError) log.Printf("error: %v\n", err) - msg := fmt.Sprintf("internal server error: %v\n", err) - RenderError(w, r, http.StatusInternalServerError, msg) + fmt.Fprintf(w, "internal server error: %v\n", err) return } isOwner := "no" @@ -196,23 +185,21 @@ func pasteGetHandlerInner(w http.ResponseWriter, r *http.Request, noRedirect, sh rawurl := string(storedPaste.Content) urlParse, err := url.Parse(rawurl) if err != nil { + w.WriteHeader(http.StatusInternalServerError) 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") - RenderError(w, r, http.StatusInternalServerError, msg) + fmt.Fprintf(w, "internal server error: invalid url in database\n") return } http.Redirect(w, r, urlParse.String(), http.StatusSeeOther) } w.Write(storedPaste.Content) case StateDeleted: - RenderError(w, r, http.StatusGone, "paste has been deleted\n") - return + w.WriteHeader(http.StatusGone) + fmt.Fprintf(w, "key has been deleted\n") default: w.WriteHeader(http.StatusInternalServerError) 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) - RenderError(w, r, http.StatusInternalServerError, msg) - return + fmt.Fprintf(w, "internal server error: invalid storedPaste.State (%v\n)", storedPaste.State) } } @@ -220,18 +207,18 @@ func shortenPostHandler(w http.ResponseWriter, r *http.Request) { rawurl := r.PostForm.Get("shorten") userURL, err := url.ParseRequestURI(rawurl) if err != nil { - msg := fmt.Sprintf("invalid url (%v): %v\n", err, rawurl) - RenderError(w, r, http.StatusBadRequest, msg) + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "invalid url (%v): %v\n", err, rawurl) return } if userURL.Scheme == "" { - msg := fmt.Sprintf("invalid url (unspecified scheme)\n", rawurl) - RenderError(w, r, http.StatusBadRequest, msg) + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "invalid url (unspecified scheme)\n", rawurl) return } if userURL.Host == "" { - msg := fmt.Sprintf("invalid url (unspecified host)\n", rawurl) - RenderError(w, r, http.StatusBadRequest, msg) + w.WriteHeader(http.StatusBadRequest) + fmt.Fprintf(w, "invalid url (unspecified host)\n", rawurl) return } @@ -250,30 +237,23 @@ func shortenPostHandler(w http.ResponseWriter, r *http.Request) { storedPaste = sp return err }); err != nil { + w.WriteHeader(http.StatusInternalServerError) log.Printf("error: %v\n", err) - msg := fmt.Sprintf("internal server error: %v\n", err) - RenderError(w, r, http.StatusInternalServerError, msg) + fmt.Fprintf(w, "internal server error: %v\n", err) return } saveURL, err := r.URL.Parse(string(storedPaste.Key)) if err != nil { - err = 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 + log.Printf("error: %v\n", errors.Wrap(err, "parsing url")) } var base64OwnerToken = make([]byte, 24) 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) } - ownerKey := 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) + fmt.Fprintf(w, "Owner key is %s\n", strings.TrimRightFunc(string(base64OwnerToken), isNotPrint)) } // Retrieve a URL from the database @@ -407,141 +387,3 @@ func getOwnerTokenFromRequest(r *http.Request) ([16]byte, bool) { } 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 -}