/
table.go
81 lines (67 loc) · 1.81 KB
/
table.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package aurion
import (
"bytes"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
type PartialResponse struct {
XMLName xml.Name `xml:"partial-response"`
Text string `xml:",chardata"`
ID string `xml:"id,attr"`
Changes struct {
Text string `xml:",chardata"`
Update []struct {
Text string `xml:",chardata"`
ID string `xml:"id,attr"`
} `xml:"update"`
} `xml:"changes"`
}
type ScrapTableOption struct {
Url string
FormOption url.Values
}
func ScrapTable(token Token, currentPage []byte, pageOptions ScrapTableOption) (string, error) {
// Set client
client := &http.Client{}
// Get view state from currentPage
reader := bytes.NewReader(currentPage)
viewState, err := getViewState(reader)
if err != nil {
return "", err
}
formData := pageOptions.FormOption
formData.Add("javax.faces.ViewState", string(viewState))
req, err := http.NewRequest("POST", pageOptions.Url, strings.NewReader(formData.Encode()))
if err != nil {
return "", err
}
req.Header.Set("Faces-Request", "partial/ajax")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Cookie", fmt.Sprintf("JSESSIONID=%v", token))
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
content, _ := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
// Convert partial response to HTML compatible array
var partialResponse PartialResponse
xml.Unmarshal(content, &partialResponse)
return convertPartialResponseToHTML(partialResponse), nil
}
func convertPartialResponseToHTML(partialResponse PartialResponse) string {
var html string
for _, update := range partialResponse.Changes.Update {
if update.ID == "form:dataTableFavori" {
html = fmt.Sprintf("<html><table>%s</table></html>", update.Text)
}
}
return html
}