Created
June 5, 2017 15:43
-
-
Save fzerorubigd/f2d9a87b639e314bf32b35bf970e9d60 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"os" | |
"time" | |
"path/filepath" | |
"github.com/elazarl/goproxy" | |
"github.com/fzerorubigd/expand" | |
) | |
type respWriter struct { | |
buf bytes.Buffer | |
Result *http.Response | |
} | |
func (rw *respWriter) Header() http.Header { | |
return rw.Result.Header | |
} | |
func (rw *respWriter) Write(p []byte) (int, error) { | |
i, err := rw.buf.Write(p) | |
rw.Result.Body = ioutil.NopCloser(&rw.buf) | |
return i, err | |
} | |
func (rw *respWriter) WriteHeader(s int) { | |
rw.Result.StatusCode = s | |
} | |
func NewRespWriter(r *http.Request) *respWriter { | |
resp := &http.Response{} | |
resp.Request = r | |
resp.TransferEncoding = r.TransferEncoding | |
resp.Header = make(http.Header) | |
return &respWriter{ | |
Result: resp, | |
} | |
} | |
func main() { | |
pwd, err := expand.Pwd() | |
if err != nil { | |
panic(err) | |
} | |
cc := filepath.Join(pwd, "cache") | |
proxy := goproxy.NewProxyHttpServer() | |
proxy.Verbose = false | |
proxy.OnRequest().DoFunc( | |
func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { | |
log.Println("=>", r.URL.String()) | |
if filepath.Ext(r.URL.Path) == ".pkg" { | |
log.Println(r.URL.Path) | |
// ok time to hack! | |
f := filepath.Join(cc, filepath.Base(r.URL.Path)) | |
if _, err := os.Stat(f); os.IsNotExist(err) { | |
log.Println(err) | |
return r, nil | |
} | |
log.Println("OK!") | |
handle, err := os.Open(f) | |
if err != nil { | |
return r, nil | |
} | |
defer handle.Close() | |
w := NewRespWriter(r) | |
http.ServeContent(w, r, f, time.Time{}, handle) | |
return r, w.Result | |
} | |
return r, nil | |
}) | |
log.Fatal(http.ListenAndServe(":8080", proxy)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment