github.com/PurpleSec/switchproxy@v1.6.2/new.go (about) 1 // Copyright 2021 - 2022 PurpleSec Team 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as published 5 // by the Free Software Foundation, either version 3 of the License, or 6 // (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <https://www.gnu.org/licenses/>. 15 // 16 17 package switchproxy 18 19 import ( 20 "bytes" 21 "context" 22 "net/http" 23 "sync" 24 "time" 25 ) 26 27 type keys struct { 28 Cert, Key string 29 } 30 31 // Timeout is a time.Duration alias of a configuration option. 32 type Timeout time.Duration 33 34 // Parameter is an interface that helps define config options for the 35 // Proxy struct. 36 type Parameter interface { 37 config(*Proxy) 38 } 39 40 func (k keys) config(p *Proxy) { 41 p.key, p.cert = k.Key, k.Cert 42 } 43 func (t Timeout) config(p *Proxy) { 44 p.server.ReadTimeout = time.Duration(t) 45 p.server.IdleTimeout, p.server.WriteTimeout = p.server.ReadTimeout, p.server.ReadTimeout 46 p.server.ReadHeaderTimeout = p.server.ReadTimeout 47 } 48 49 // TLS creates a config parameter with the specified Key and Value file paths. 50 func TLS(cert, key string) Parameter { 51 return &keys{Cert: cert, Key: key} 52 } 53 54 // New creates a new Proxy instance from the specified listen address and 55 // optional parameters. 56 func New(listen string, c ...Parameter) *Proxy { 57 return NewContext(context.Background(), listen, c...) 58 } 59 60 // NewContext creates a new Proxy instance from the specified listen address and 61 // optional parameters. 62 // 63 // This function allows the caller to specify a context to specify when to shut down 64 // the Proxy. 65 func NewContext(x context.Context, listen string, c ...Parameter) *Proxy { 66 p := &Proxy{ 67 pool: &sync.Pool{ 68 New: func() interface{} { 69 return &transfer{out: new(bytes.Buffer), read: new(bytes.Buffer)} 70 }, 71 }, 72 server: &http.Server{Addr: listen, Handler: &http.ServeMux{}}, 73 secondary: make([]*Switch, 0), 74 } 75 p.server.BaseContext = p.context 76 p.ctx, p.cancel = context.WithCancel(x) 77 p.server.Handler.(*http.ServeMux).Handle("/", p) 78 for i := range c { 79 c[i].config(p) 80 } 81 if len(c) == 0 { 82 p.server.ReadTimeout, p.server.IdleTimeout = DefaultTimeout, DefaultTimeout 83 p.server.WriteTimeout, p.server.ReadHeaderTimeout = DefaultTimeout, DefaultTimeout 84 } 85 return p 86 }