package auth import ( "encoding/json" "net/http" "net/http/cookiejar" "net/url" "github.com/zalando/go-keyring" ) const service = "knit://" // NewClient creates a new http.Client with the appropriate authentication set func NewClient(host string, handle string) (*http.Client, error) { cookies, err := getCookies(host, handle) if err != nil { return nil, err } // cookiejar.New can't fail jar, _ := cookiejar.New(nil) u := &url.URL{ Scheme: "https", Host: host, } jar.SetCookies(u, cookies) return &http.Client{Jar: jar}, nil } // SaveCookies serializes the cookies and saves them to the system keyring func SaveCookies(cookies []*http.Cookie, host string, handle string) error { if len(cookies) == 0 { return nil } data, err := json.Marshal(cookies) if err != nil { return err } return keyring.Set(service+host, handle, string(data)) } func getCookies(host string, handle string) ([]*http.Cookie, error) { s, err := keyring.Get(service+host, handle) if err != nil { return nil, err } var cookies []*http.Cookie if err := json.Unmarshal([]byte(s), &cookies); err != nil { return nil, err } return cookies, nil }