attachments.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package controllers
  2. import (
  3. "fmt"
  4. "github.com/Jinnrry/pmail/dto/response"
  5. "github.com/Jinnrry/pmail/services/attachments"
  6. "github.com/Jinnrry/pmail/utils/context"
  7. "github.com/spf13/cast"
  8. "net/http"
  9. "strings"
  10. )
  11. func GetAttachments(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
  12. urlInfos := strings.Split(req.RequestURI, "/")
  13. if len(urlInfos) != 4 {
  14. response.NewErrorResponse(response.ParamsError, "", "").FPrint(w)
  15. return
  16. }
  17. emailId := cast.ToInt(urlInfos[2])
  18. cid := urlInfos[3]
  19. contentType, content := attachments.GetAttachments(ctx, emailId, cid)
  20. if len(content) == 0 {
  21. response.NewErrorResponse(response.ParamsError, "", "").FPrint(w)
  22. return
  23. }
  24. w.Header().Set("Content-Type", contentType)
  25. w.Write(content)
  26. }
  27. func Download(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
  28. urlInfos := strings.Split(req.RequestURI, "/")
  29. if len(urlInfos) != 5 {
  30. response.NewErrorResponse(response.ParamsError, "", "").FPrint(w)
  31. return
  32. }
  33. emailId := cast.ToInt(urlInfos[3])
  34. index := cast.ToInt(urlInfos[4])
  35. fileName, content := attachments.GetAttachmentsByIndex(ctx, emailId, index)
  36. if len(content) == 0 {
  37. response.NewErrorResponse(response.ParamsError, "", "").FPrint(w)
  38. return
  39. }
  40. w.Header().Set("ContentType", "application/octet-stream")
  41. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment;filename=%s", fileName))
  42. w.Write(content)
  43. }