diff --git a/broker/broker.go b/broker/broker.go index 38fea0a..0d7a37c 100644 --- a/broker/broker.go +++ b/broker/broker.go @@ -2,9 +2,15 @@ package broker import ( "context" + "encoding/json" + "errors" + "local/storage" "local/truckstop/config" + "local/truckstop/logtr" "net/http" + "net/http/cookiejar" "strings" + "time" "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") { 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) } diff --git a/broker/broker_test.go b/broker/broker_test.go new file mode 100644 index 0000000..703c20a --- /dev/null +++ b/broker/broker_test.go @@ -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") +}