Contains the Concourse pipeline definition for building a line-server container
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
2.2 KiB

9 years ago
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "os"
  8. "path"
  9. "regexp"
  10. "strings"
  11. "code.google.com/p/go-uuid/uuid"
  12. "github.com/zenazn/goji/web"
  13. )
  14. type UploadRequest struct {
  15. src io.Reader
  16. filename string
  17. expiry int
  18. randomBarename bool
  19. }
  20. type Upload struct {
  21. Filename string
  22. Size int64
  23. Expiry int
  24. }
  25. func uploadPostHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  26. upReq := UploadRequest{}
  27. file, headers, err := r.FormFile("file")
  28. if err != nil {
  29. fmt.Fprintf(w, err.Error())
  30. return
  31. }
  32. defer file.Close()
  33. upReq.src = file
  34. upReq.filename = headers.Filename
  35. upload, err := processUpload(upReq)
  36. if err != nil {
  37. fmt.Fprintf(w, "Failed to upload: %v", err)
  38. return
  39. }
  40. fmt.Fprintf(w, "File %s uploaded successfully.", upload.Filename)
  41. }
  42. func uploadPutHandler(c web.C, w http.ResponseWriter, r *http.Request) {
  43. upReq := UploadRequest{}
  44. defer r.Body.Close()
  45. upReq.src = r.Body
  46. upload, err := processUpload(upReq)
  47. if err != nil {
  48. fmt.Fprintf(w, "Failed to upload")
  49. return
  50. }
  51. fmt.Fprintf(w, "File %s uploaded successfully.", upload.Filename)
  52. }
  53. func processUpload(upReq UploadRequest) (upload Upload, err error) {
  54. barename, extension := barePlusExt(upReq.filename)
  55. if upReq.randomBarename || len(barename) == 0 {
  56. barename = generateBarename()
  57. }
  58. if len(extension) == 0 {
  59. extension = "ext"
  60. }
  61. upload.Filename = strings.Join([]string{barename, extension}, ".")
  62. dst, ferr := os.Create(path.Join("files/", upload.Filename))
  63. defer dst.Close()
  64. if ferr != nil {
  65. err = ferr
  66. return
  67. }
  68. bytes, cerr := io.Copy(dst, upReq.src)
  69. if cerr != nil {
  70. err = cerr
  71. return
  72. } else if bytes == 0 {
  73. err = errors.New("Empty file")
  74. return
  75. }
  76. upload.Size = bytes
  77. return
  78. }
  79. func generateBarename() string {
  80. return uuid.New()[:8]
  81. }
  82. func barePlusExt(filename string) (barename, extension string) {
  83. re := regexp.MustCompile(`[^A-Za-z0-9\-]`)
  84. filename = strings.TrimSpace(filename)
  85. filename = strings.ToLower(filename)
  86. extension = path.Ext(filename)
  87. barename = filename[:len(filename)-len(extension)]
  88. extension = re.ReplaceAllString(extension, "")
  89. barename = re.ReplaceAllString(barename, "")
  90. return
  91. }