summaryrefslogtreecommitdiff
path: root/wget.go
blob: a1ecef0a9169e78dba53c33b986b17c37bb7d03d (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package shell

/* 
	This simply parses the command line arguments using the default golang
	package called 'flag'. This can be used as a simple template to parse
	command line arguments in other programs.

	It puts everything in a 'config' Protobuf which I think is a good
	wrapper around the 'flags' package and doesn't need a whole mess of
	global variables
*/

import (
	"io"
	"os"
	"fmt"
	"bytes"
	"strings"
	"net/http"

	"go.wit.com/log"
)

func Wget(url string) (*bytes.Buffer) {
	buf := new(bytes.Buffer)

	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		handleError(err, -1)
		return nil
	}
	defer resp.Body.Close()

	log.Log(INFO, "res.StatusCode: %d\n", resp.StatusCode)
	if (resp.StatusCode != 200) {
		handleError(fmt.Errorf(fmt.Sprint("%d", resp.StatusCode)), -1)
		return nil
	}

	buf.ReadFrom(resp.Body)
	return buf
}

func WgetToFile(filepath string, url string) error {
	log.Log(INFO, "WgetToFile() filepath =", filepath)
	log.Log(INFO, "WgetToFile() URL =", url)
	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		handleError(err, -1)
		return err
	}
	defer resp.Body.Close()

	// Create the file
	out, err := os.Create(filepath)
	if err != nil {
		handleError(err, -1)
		return err
	}
	defer out.Close()

	// Write the body to file
	_, err = io.Copy(out, resp.Body)
	return err
}

// write out a file. Always be nice and end with '\n'
// if you are here and want to complain about ending in '\n'
// then you probably aren't going to like lots of things in this
// package. I will quote the evilwm man page:
//
// BUGS: The author's idea of friendly may differ to that of many other people.
//
func Write(filepath string, data string) bool {
	// TODO: this isn't working for some reason and is making two '\n' chars
	// probably because Chomp() isn't fixed yet
	data = Chomp(data) + "\n"
	// Create the file
	ospath := Path(filepath)
	log.Log(INFO, "shell.Write() START ospath =", ospath, "filepath =", filepath)
	out, err := os.Create(ospath)
	if err != nil {
		return false
	}
	defer out.Close()

	// Write the body to file
	// _, err = io.Copy(out, resp.Body)
	count, err := io.Copy(out, strings.NewReader(data))
	if err != nil {
		handleError(err, -1)
		return false
	}
	handleError(nil, int(count))
	log.Log(INFO, "shell.Write() END", ospath)
	return true
}