main.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "image"
  8. "log"
  9. "net/http"
  10. "net/url"
  11. "strconv"
  12. "strings"
  13. "time"
  14. )
  15. type httpHandler struct{}
  16. func parsePath(r *http.Request) (string, processingOptions, error) {
  17. var po processingOptions
  18. var err error
  19. path := r.URL.Path
  20. parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
  21. if len(parts) < 7 {
  22. return "", po, errors.New("Invalid path")
  23. }
  24. token := parts[0]
  25. if err = validatePath(token, strings.TrimPrefix(path, fmt.Sprintf("/%s", token))); err != nil {
  26. return "", po, err
  27. }
  28. po.resize = parts[1]
  29. if po.width, err = strconv.Atoi(parts[2]); err != nil {
  30. return "", po, fmt.Errorf("Invalid width: %s", parts[2])
  31. }
  32. if po.height, err = strconv.Atoi(parts[3]); err != nil {
  33. return "", po, fmt.Errorf("Invalid height: %s", parts[3])
  34. }
  35. if g, ok := gravityTypes[parts[4]]; ok {
  36. po.gravity = g
  37. } else {
  38. return "", po, fmt.Errorf("Invalid gravity: %s", parts[4])
  39. }
  40. po.enlarge = parts[5] != "0"
  41. filenameParts := strings.Split(strings.Join(parts[6:], ""), ".")
  42. if len(filenameParts) < 2 {
  43. po.format = imageTypes["jpg"]
  44. } else if f, ok := imageTypes[filenameParts[1]]; ok {
  45. po.format = f
  46. } else {
  47. return "", po, fmt.Errorf("Invalid image format: %s", filenameParts[1])
  48. }
  49. filename, err := base64.RawURLEncoding.DecodeString(filenameParts[0])
  50. if err != nil {
  51. return "", po, errors.New("Invalid filename encoding")
  52. }
  53. return string(filename), po, nil
  54. }
  55. func imageContentType(b []byte) string {
  56. _, imgtype, _ := image.DecodeConfig(bytes.NewReader(b))
  57. return fmt.Sprintf("image/%s", imgtype)
  58. }
  59. func logResponse(status int, msg string) {
  60. var color int
  61. if status > 500 {
  62. color = 31
  63. } else if status > 400 {
  64. color = 33
  65. } else {
  66. color = 32
  67. }
  68. log.Printf("|\033[7;%dm %d \033[0m| %s\n", color, status, msg)
  69. }
  70. func respondWithImage(rw http.ResponseWriter, data []byte, imgURL string, po processingOptions) {
  71. logResponse(200, fmt.Sprintf("Processed: %s; %+v", imgURL, po))
  72. rw.WriteHeader(200)
  73. rw.Header().Set("Content-Type", imageContentType(data))
  74. rw.Write(data)
  75. }
  76. func respondWithError(rw http.ResponseWriter, status int, err error, msg string) {
  77. logResponse(status, err.Error())
  78. rw.WriteHeader(status)
  79. rw.Write([]byte(msg))
  80. }
  81. func (h httpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  82. log.Printf("GET: %s\n", r.URL.RequestURI())
  83. imgURL, procOpt, err := parsePath(r)
  84. if err != nil {
  85. respondWithError(rw, 404, err, "Invalid image url")
  86. return
  87. }
  88. if _, err = url.ParseRequestURI(imgURL); err != nil {
  89. respondWithError(rw, 404, err, "Invalid image url")
  90. return
  91. }
  92. b, err := downloadImage(imgURL)
  93. if err != nil {
  94. respondWithError(rw, 404, err, "Image is unreacable")
  95. return
  96. }
  97. b, err = processImage(b, procOpt)
  98. if err != nil {
  99. respondWithError(rw, 500, err, "Error occured while processing image")
  100. return
  101. }
  102. respondWithImage(rw, b, imgURL, procOpt)
  103. }
  104. func main() {
  105. s := &http.Server{
  106. Addr: conf.Bind,
  107. Handler: httpHandler{},
  108. ReadTimeout: time.Duration(conf.ReadTimeout) * time.Second,
  109. WriteTimeout: time.Duration(conf.WriteTimeout) * time.Second,
  110. MaxHeaderBytes: 1 << 20,
  111. }
  112. log.Printf("Starting server at %s\n", conf.Bind)
  113. log.Fatal(s.ListenAndServe())
  114. }