Created
April 4, 2016 08:45
-
-
Save tynor/343cb1d2d8befc7712f8a4f73b2a8d50 to your computer and use it in GitHub Desktop.
This file contains 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" | |
"compress/gzip" | |
"fmt" | |
"io" | |
"net/http" | |
"os" | |
"time" | |
) | |
// general error type that | |
// will hold the custom message | |
// plus business error logic | |
type genErr struct { | |
message string | |
err error | |
} | |
// make genError implement the error interface:w | |
func (g genErr) Error() string { | |
return fmt.Sprintf("%s with the following error %s", g.message, g.err.Error()) | |
} | |
// create a new cunstom request setting | |
// headers and body | |
func newCustomRequest(method, url string) (*http.Request, error) { | |
req, err := http.NewRequest(method, url, new(bytes.Buffer)) | |
if err != nil { | |
return nil, &genErr{ | |
message: fmt.Sprintf("Can't create this custom request with method %s, and url %s", method, url), | |
err: err, | |
} | |
} | |
req.Header.Add("User-Agent", "LinkTracker1.0.0") | |
req.Header.Add("Cache-Control", "no-cache") | |
req.Header.Add("Connection", "close") | |
req.Header.Add("Accept", "text/html") | |
req.Header.Add("Accept-Charset", "utf8") | |
req.Header.Add("Accept-Encoding", "gzip") | |
return req, nil | |
} | |
// create a new custom client with a specific timeout duration | |
// on every request | |
func newCustomClient(time time.Duration) *http.Client { | |
return &http.Client{ | |
Timeout: time, | |
} | |
} | |
func main() { | |
req, err := newCustomRequest("GET", "http://www.kama.net") | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
// make new http Client object | |
// setting the timeout duration for every request | |
cli := newCustomClient(5 * time.Second) | |
// make the request | |
resp, err := cli.Do(req) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
defer resp.Body.Close() | |
switch resp.StatusCode { | |
case 200: | |
reader, err := gzip.NewReader(resp.Body) | |
if err != nil { | |
fmt.Fprintln(os.Stderr, err) | |
os.Exit(1) | |
} | |
defer reader.Close() | |
n, err := io.Copy(os.Stdout, reader) | |
if err != nil { | |
fmt.Fprintln(os.Stderr, err) | |
os.Exit(1) | |
} | |
fmt.Println("") | |
fmt.Println(n) | |
default: | |
fmt.Fprintf(os.Stderr, "Error occured with status %d ", resp.StatusCode) | |
os.Exit(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment