main.go 3.5 KB

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