utils.go 1.99 KB
Newer Older
Fernando Avilés's avatar
Fernando Avilés committed
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
package utils

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"
	"strings"

	"github.com/tdewolff/minify"
	"github.com/tdewolff/minify/css"
	"github.com/tdewolff/minify/html"
)

//Funcion que crea carpeta o carpteas
func CreateDirectory(path string) error {
	var err error
	if _, err = os.Stat(path); os.IsNotExist(err) {
		err = os.MkdirAll(path, 0775)
	}
	return err
}

// Funcion que borrar una carpeta y todo su contenido
func DeleteDirecotory(path string) error {
	dirRead, _ := os.Open(path)
	dirFiles, _ := dirRead.Readdir(0)
	for index := range dirFiles {
		fileHere := dirFiles[index]
		// Get name of file and its full path.
		nameHere := fileHere.Name()
		fullPath := path + nameHere
		// Remove the file.
		os.Remove(fullPath)
	}
	return os.Remove(path)
}

// Funcion que borrar una carpeta y su contenido
func DeleteFile(fullPath string) error {
	return os.Remove(fullPath)
}

//  Obtiene el html de una url
func GetUrlContent(url string) (string, error) {
	var (
		err     error
		content []byte
		resp    *http.Response
	)

	// GET content of URL
	if resp, err = http.Get(url); err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// Check if request was successful
	if resp.StatusCode != 200 {
		return strconv.Itoa(resp.StatusCode), err
	}

	// Read the body of the HTTP response
	if content, err = ioutil.ReadAll(resp.Body); err != nil {
		return "", err
	}
	return string(content), err
}

// Escribe un archivo en el servidor
//
func WriteHTML(hmtlNota *string, path string) error {
	return ioutil.WriteFile(path, []byte(*hmtlNota), 0664)
}

// Minifica el html
func MinifyHTML(htmlNota *string) error {
	m := minify.New()
	m.AddFunc("text/html", html.Minify)
	m.AddFunc("text/css", css.Minify)
	m.Add("text/html", &html.Minifier{
		KeepEndTags:             true,
		KeepDocumentTags:        true,
		KeepConditionalComments: true,
		KeepDefaultAttrVals:     true,
	})

	r := strings.NewReader(*htmlNota)
	buf := &bytes.Buffer{}
	err := m.Minify("text/html", buf, r)
	*htmlNota = buf.String()
	return err
}