master
bel 2022-01-27 10:38:41 -07:00
parent a127d9fd25
commit 60c88375ad
2 changed files with 77 additions and 1 deletions

View File

@ -2,9 +2,15 @@ package broker
import ( import (
"context" "context"
"encoding/json"
"errors"
"local/storage"
"local/truckstop/config" "local/truckstop/config"
"local/truckstop/logtr"
"net/http" "net/http"
"net/http/cookiejar"
"strings" "strings"
"time"
"golang.org/x/time/rate" "golang.org/x/time/rate"
) )
@ -24,5 +30,54 @@ func do(r *http.Request) (*http.Response, error) {
if strings.Contains(strings.ToLower(r.URL.Path), "login") { if strings.Contains(strings.ToLower(r.URL.Path), "login") {
authlimiter.Wait(context.Background()) authlimiter.Wait(context.Background())
} }
return http.DefaultClient.Do(r) client := &http.Client{
Timeout: time.Hour,
}
newjar, err := cookiejar.New(&cookiejar.Options{})
if err != nil {
return nil, errors.New("failed to make a cookie jar: " + err.Error())
}
client.Jar = newjar
cookieJarKey := r.URL.Host
cookies, err := getCookies(cookieJarKey)
if err != nil {
logtr.Errorf("failed to load cookies: %v", err)
} else {
client.Jar.SetCookies(r.URL, cookies)
}
resp, err := client.Do(r)
if err != nil {
return nil, err
}
if err := setCookies(cookieJarKey, client.Jar.Cookies(r.URL)); err != nil {
logtr.Errorf("failed to set cookies: %v", err)
}
return resp, err
}
func getCookies(host string) ([]*http.Cookie, error) {
return _getCookies(config.Get().DB(), host)
}
func _getCookies(db storage.DB, host string) ([]*http.Cookie, error) {
b, err := db.Get(host)
if err != nil {
return nil, err
}
var result []*http.Cookie
err = json.Unmarshal(b, &result)
return result, err
}
func setCookies(host string, cookies []*http.Cookie) error {
return _setCookies(config.Get().DB(), host, cookies)
}
func _setCookies(db storage.DB, host string, cookies []*http.Cookie) error {
b, err := json.Marshal(cookies)
if err != nil {
return err
}
return db.Set(host, b)
} }

21
broker/broker_test.go Normal file
View File

@ -0,0 +1,21 @@
package broker
import (
"local/storage"
"testing"
)
func TestDoCookies(t *testing.T) {
// func _setCookies(db storage.DB, host string, cookies []*http.Cookie) error {
// func _getCookies(db storage.DB, host string) cookies, error {
db := storage.NewMap()
host := "host"
if cookies, err := _getCookies(db, host); err == nil {
t.Fatal(err)
} else if len(cookies) != 0 {
t.Fatal(cookies)
}
t.Fatal("not impl")
}