-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathresponse.go
66 lines (52 loc) · 1.12 KB
/
response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package tinypng
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
)
// Response from the TinyPNG API
type Response struct {
Input Input
Output Output
Error string
Message string
URL string
}
// Input size
type Input struct {
Size int32
}
// Output size, ratio and url
type Output struct {
Size int32
Ratio float64
}
// PopulateFromHTTPResponse populates response based on HTTP response
func (r *Response) PopulateFromHTTPResponse(res *http.Response) {
body, err := ioutil.ReadAll(res.Body)
check(err)
err = json.Unmarshal(body, &r)
check(err)
// Get the output URL from the Location header
r.URL = res.Header.Get("Location")
}
// SaveAs downloads and saves the compressed PNG file
func (r *Response) SaveAs(fn string) {
resp, err := http.Get(r.URL)
check(err)
defer resp.Body.Close()
out, err := os.Create(fn)
check(err)
defer out.Close()
io.Copy(out, resp.Body)
}
// Print a line of statistics
func (r *Response) Print() {
fmt.Print("Input size: ", r.Input.Size)
fmt.Print(" Output size: ", r.Output.Size)
fmt.Println(" Ratio:", r.Output.Ratio)
fmt.Println("\n", r.URL)
}