github.com/greenpau/go-authcrunch@v1.1.4/pkg/util/browser.go (about) 1 // Copyright 2022 Paul Greenberg greenpau@outlook.com 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package util 16 17 import ( 18 "io/ioutil" 19 "net" 20 "net/http" 21 "net/http/cookiejar" 22 "time" 23 ) 24 25 // Browser represents a browser instance. 26 type Browser struct { 27 client *http.Client 28 } 29 30 // NewBrowser returns an instance of a browser. 31 func NewBrowser() (*Browser, error) { 32 cj, err := cookiejar.New(nil) 33 if err != nil { 34 return nil, err 35 } 36 tr := &http.Transport{ 37 Proxy: http.ProxyFromEnvironment, 38 Dial: (&net.Dialer{ 39 Timeout: 5 * time.Second, 40 }).Dial, 41 TLSHandshakeTimeout: 5 * time.Second, 42 } 43 b := &Browser{ 44 client: &http.Client{ 45 Jar: cj, 46 Timeout: time.Second * 10, 47 Transport: tr, 48 CheckRedirect: func(req *http.Request, via []*http.Request) error { 49 return http.ErrUseLastResponse 50 }, 51 }, 52 } 53 return b, nil 54 } 55 56 // Do makes HTTP requests and parses responses. 57 func (b *Browser) Do(req *http.Request) (string, *http.Response, error) { 58 req.Header.Set("User-Agent", "authdbctl/1.0.16") 59 resp, err := b.client.Do(req) 60 if err != nil { 61 return "", nil, err 62 } 63 64 respBody, err := ioutil.ReadAll(resp.Body) 65 resp.Body.Close() 66 if err != nil { 67 return "", nil, err 68 } 69 70 return string(respBody), resp, nil 71 }