100 lines
2.2 KiB
Go
100 lines
2.2 KiB
Go
package remote
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"net/http/cookiejar"
|
|
"net/url"
|
|
"strings"
|
|
)
|
|
|
|
type HTTP struct {
|
|
client *http.Client
|
|
domain string
|
|
password string
|
|
}
|
|
|
|
func NewHTTP(domain, password string) (*HTTP, error) {
|
|
j, _ := cookiejar.New(nil)
|
|
//Transport: &http.Transport{Proxy: http.ProxyURL(&url.URL{
|
|
// Host: "localhost:8890",
|
|
// Scheme: "http",
|
|
//})},
|
|
h := &HTTP{
|
|
client: &http.Client{
|
|
Jar: j,
|
|
},
|
|
domain: domain,
|
|
password: password,
|
|
}
|
|
if resp, err := h.Get("/"); err != nil {
|
|
return nil, err
|
|
} else if resp.StatusCode != 200 {
|
|
return nil, fmt.Errorf("bad status from endpoint: %v", resp.StatusCode)
|
|
}
|
|
if password != "" {
|
|
form := url.Values{}
|
|
form.Add("login", "1")
|
|
form.Add("password", password)
|
|
if resp, err := h.Post("ajax.php?login", form.Encode()); err != nil {
|
|
return nil, err
|
|
} else if b, _ := ioutil.ReadAll(resp.Body); string(b) == `{"logged":0}` {
|
|
return nil, fmt.Errorf("bad password")
|
|
} else if string(b) != `{"logged":1}` {
|
|
return nil, fmt.Errorf("bad login: %q", b)
|
|
}
|
|
if resp, err := h.Get("/"); err != nil {
|
|
return nil, err
|
|
} else if resp.StatusCode != 200 {
|
|
return nil, fmt.Errorf("bad status from endpoint: %v", resp.StatusCode)
|
|
}
|
|
}
|
|
return h, nil
|
|
}
|
|
|
|
func (h *HTTP) Get(path string) (*http.Response, error) {
|
|
req, err := h.NewReq("GET", path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return h.Do(req)
|
|
}
|
|
|
|
func (h *HTTP) Post(path, body string) (*http.Response, error) {
|
|
req, err := h.NewReq("POST", path, body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return h.Do(req)
|
|
}
|
|
|
|
func (h *HTTP) Do(req *http.Request) (*http.Response, error) {
|
|
resp, err := h.client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return resp, nil
|
|
}
|
|
|
|
func (h *HTTP) NewReq(method string, pathAndBody ...string) (*http.Request, error) {
|
|
path := ""
|
|
var bodyReader io.Reader
|
|
if len(pathAndBody) > 0 {
|
|
path = pathAndBody[0]
|
|
}
|
|
if !strings.HasPrefix(path, "/") {
|
|
path = "/" + path
|
|
}
|
|
if len(pathAndBody) > 1 {
|
|
bodyReader = strings.NewReader(pathAndBody[1])
|
|
}
|
|
r, err := http.NewRequest(method, h.domain+path, bodyReader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
|
return r, nil
|
|
}
|