gin_favicon.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package http_middleware
  2. import (
  3. "bytes"
  4. "github.com/gin-gonic/gin"
  5. "io/ioutil"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. )
  10. func Favicon(path string) gin.HandlerFunc {
  11. path = filepath.FromSlash(path)
  12. if len(path) > 0 && !os.IsPathSeparator(path[0]) {
  13. wd, err := os.Getwd()
  14. if err != nil {
  15. panic(err)
  16. }
  17. path = filepath.Join(wd, path)
  18. }
  19. info, err := os.Stat(path)
  20. if err != nil || info == nil || info.IsDir() {
  21. panic("Invalid favicon path: " + path)
  22. }
  23. file, err := ioutil.ReadFile(path)
  24. if err != nil {
  25. panic(err)
  26. }
  27. reader := bytes.NewReader(file)
  28. return func(ctxt *gin.Context) {
  29. if ctxt.Request.RequestURI != "/favicon.ico" {
  30. ctxt.Next()
  31. return
  32. }
  33. if ctxt.Request.Method != "GET" && ctxt.Request.Method != "HEAD" {
  34. status := http.StatusOK
  35. if ctxt.Request.Method != "OPTIONS" {
  36. status = http.StatusMethodNotAllowed
  37. }
  38. ctxt.Header("Allow", "GET,HEAD,OPTIONS")
  39. ctxt.AbortWithStatus(status)
  40. ctxt.Abort()
  41. return
  42. }
  43. ctxt.Header("Content-Type", "image/x-icon")
  44. http.ServeContent(ctxt.Writer, ctxt.Request, "favicon.ico", info.ModTime(), reader)
  45. ctxt.Abort()
  46. }
  47. }