From 7a54d5d94e209e05dbafbff9e8276227574f9007 Mon Sep 17 00:00:00 2001 From: suxianbaozi Date: Fri, 12 Nov 2021 15:52:30 +0800 Subject: [PATCH] sample certstorage --- examples/goproxy-certstorage/README.md | 5 ++++ examples/goproxy-certstorage/main.go | 26 +++++++++++++++++++ examples/goproxy-certstorage/storage.go | 34 +++++++++++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 examples/goproxy-certstorage/README.md create mode 100644 examples/goproxy-certstorage/main.go create mode 100644 examples/goproxy-certstorage/storage.go diff --git a/examples/goproxy-certstorage/README.md b/examples/goproxy-certstorage/README.md new file mode 100644 index 00000000..b8213681 --- /dev/null +++ b/examples/goproxy-certstorage/README.md @@ -0,0 +1,5 @@ +# certstorage + +## use certstorage + +## this could make https proxy faster diff --git a/examples/goproxy-certstorage/main.go b/examples/goproxy-certstorage/main.go new file mode 100644 index 00000000..a010a143 --- /dev/null +++ b/examples/goproxy-certstorage/main.go @@ -0,0 +1,26 @@ +package main + +import ( + "flag" + "github.com/elazarl/goproxy" + "log" + "net/http" +) + +func main() { + verbose := flag.Bool("v", false, "should every proxy request be logged to stdout") + addr := flag.String("addr", ":8080", "proxy listen address") + flag.Parse() + + proxy := goproxy.NewProxyHttpServer() + proxy.CertStore = NewCertStorage() //设置storage + + proxy.Verbose = *verbose + + proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm) + proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { + log.Println(req.URL.String()) + return req, nil + }) + log.Fatal(http.ListenAndServe(*addr, proxy)) +} diff --git a/examples/goproxy-certstorage/storage.go b/examples/goproxy-certstorage/storage.go new file mode 100644 index 00000000..5593d854 --- /dev/null +++ b/examples/goproxy-certstorage/storage.go @@ -0,0 +1,34 @@ +package main + +import ( + "crypto/tls" + "sync" +) + +type CertStorage struct { + certs sync.Map +} + +func (tcs *CertStorage) Fetch(hostname string, gen func() (*tls.Certificate, error)) (*tls.Certificate, error) { + var cert tls.Certificate + icert, ok := tcs.certs.Load(hostname) + if ok { + cert = icert.(tls.Certificate) + } else { + certp, err := gen() + if err != nil { + return nil, err + } + // store as concrete implementation + cert = *certp + tcs.certs.Store(hostname, cert) + } + return &cert, nil +} + +func NewCertStorage() *CertStorage { + tcs := &CertStorage{} + tcs.certs = sync.Map{} + + return tcs +}