| 79 | } |
| 80 | |
| 81 | func (p *ProxyServer) Handler() func(http.ResponseWriter, *http.Request) { |
| 82 | return func(w http.ResponseWriter, r *http.Request) { |
| 83 | if p.OverwriteFolder != "" && r.Method == http.MethodGet { |
| 84 | paths := []string{p.OverwriteFolder} |
| 85 | paths = append(paths, strings.Split(strings.TrimLeft(r.URL.Path, "/"), "/")...) |
| 86 | |
| 87 | proxyFilePath := filepath.Join(paths...) |
| 88 | |
| 89 | fInfo, err := os.Stat(proxyFilePath) |
| 90 | |
| 91 | // proxy request if file is not exist |
| 92 | if os.IsNotExist(err) { |
| 93 | p.proxy.ServeHTTP(w, r) |
| 94 | return |
| 95 | } |
| 96 | |
| 97 | if err != nil { |
| 98 | if strings.Contains(err.Error(), "file name too long") { |
| 99 | p.proxy.ServeHTTP(w, r) |
| 100 | return |
| 101 | } else { |
| 102 | w.WriteHeader(http.StatusInternalServerError) |
| 103 | w.Write([]byte(fmt.Sprintf("%+v\n", errors.WithStack(err)))) |
| 104 | return |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | if fInfo.IsDir() { |
| 109 | p.proxy.ServeHTTP(w, r) |
| 110 | return |
| 111 | } |
| 112 | |
| 113 | f, err := os.Open(proxyFilePath) |
| 114 | |
| 115 | // proxy request if file is not exist |
| 116 | if os.IsNotExist(err) { |
| 117 | p.proxy.ServeHTTP(w, r) |
| 118 | return |
| 119 | } |
| 120 | |
| 121 | if err != nil { |
| 122 | w.WriteHeader(http.StatusInternalServerError) |
| 123 | w.Write([]byte(fmt.Sprintf("%+v\n", errors.WithStack(err)))) |
| 124 | return |
| 125 | } |
| 126 | |
| 127 | defer f.Close() |
| 128 | |
| 129 | MIMEType := mime.TypeByExtension(filepath.Ext(proxyFilePath)) |
| 130 | |
| 131 | w.Header().Set("Content-Type", MIMEType) |
| 132 | w.WriteHeader(http.StatusOK) |
| 133 | |
| 134 | _, _ = io.Copy(w, f) |
| 135 | } else { |
| 136 | p.proxy.ServeHTTP(w, r) |
| 137 | } |
| 138 | } |