兼容OSS回源策略
This commit is contained in:
		
							
								
								
									
										31
									
								
								bin/main.go
									
									
									
									
									
								
							
							
						
						
									
										31
									
								
								bin/main.go
									
									
									
									
									
								
							@@ -65,6 +65,37 @@ func main() {
 | 
				
			|||||||
		w.Write(data)
 | 
							w.Write(data)
 | 
				
			||||||
	})
 | 
						})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// URL 格式: /webp/{type}-{id}-{version}-{width}-{height}-{fit}.{format}
 | 
				
			||||||
 | 
						http.HandleFunc("/webp/", func(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
							log.Println(r.Method, r.URL.Path)
 | 
				
			||||||
 | 
							reg := regexp.MustCompile(`^/webp/([0-9a-zA-Z]+)-([0-9a-zA-Z]+)-([0-9a-zA-Z]+)-([0-9]+)-([0-9]+)-([a-zA-Z]+).(jpg|jpeg|png|webp)$`)
 | 
				
			||||||
 | 
							matches := reg.FindStringSubmatch(r.URL.Path)
 | 
				
			||||||
 | 
							if len(matches) != 4 {
 | 
				
			||||||
 | 
								log.Println("URL 格式错误", matches)
 | 
				
			||||||
 | 
								w.WriteHeader(http.StatusNotFound)
 | 
				
			||||||
 | 
								return
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							group, id, version, width, height, fit, format := matches[1], matches[2], matches[3], stringToInt(matches[4], 0), stringToInt(matches[5], 0), matches[6], matches[7]
 | 
				
			||||||
 | 
							content, err := mysqlConnection.GetImageContent(group, id)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								log.Println("获取图片失败", version, format, err)
 | 
				
			||||||
 | 
								w.WriteHeader(http.StatusNotFound)
 | 
				
			||||||
 | 
								return
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							var img models.Image
 | 
				
			||||||
 | 
							img.Init(content)
 | 
				
			||||||
 | 
							data, err := img.ToWebP(width, height, fit)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								log.Println("转换图片失败", err)
 | 
				
			||||||
 | 
								w.WriteHeader(http.StatusBadRequest)
 | 
				
			||||||
 | 
								return
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							w.Header().Set("Content-Type", "image/webp")
 | 
				
			||||||
 | 
							w.Header().Set("Cache-Control", "max-age=31536000")
 | 
				
			||||||
 | 
							w.Write(data)
 | 
				
			||||||
 | 
						})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	log.Println("Server is running at http://localhost:6001")
 | 
						log.Println("Server is running at http://localhost:6001")
 | 
				
			||||||
	http.ListenAndServe(":6001", nil)
 | 
						http.ListenAndServe(":6001", nil)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
		Reference in New Issue
	
	Block a user