Files
kleiax 904d14b64c
CI / test (push) Canceled after 0s
Initial commit
2026-09-12 22:22:17 +02:00

44 lines
1.4 KiB
Go

package client
import (
"context"
"net/http"
)
// CreateSession logs in and stores the returned cookie when the client was
// configured with sessions. response.Cookies() can be forwarded by a web
// frontend to its browser.
func (c *Client) CreateSession(ctx context.Context, credentials Credentials) (User, *Response, error) {
var envelope struct {
User User `json:"user"`
}
response, err := c.do(ctx, http.MethodPost, "v1/session", credentials, &envelope)
return envelope.User, response, err
}
// Session returns the user associated with the current session cookie.
func (c *Client) Session(ctx context.Context) (User, *Response, error) {
var envelope struct {
User User `json:"user"`
}
response, err := c.do(ctx, http.MethodGet, "v1/session", nil, &envelope)
return envelope.User, response, err
}
// DeleteSession logs out. Forward response.Cookies() to the browser so its
// session cookie is removed as well.
func (c *Client) DeleteSession(ctx context.Context) (*Response, error) {
return c.do(ctx, http.MethodDelete, "v1/session", nil, nil)
}
// ForwardCookies copies API Set-Cookie headers to a frontend response. It is
// intended for the Response returned by CreateSession or DeleteSession.
func ForwardCookies(w http.ResponseWriter, response *Response) {
if w == nil || response == nil || response.Response == nil {
return
}
for _, cookie := range response.Cookies() {
http.SetCookie(w, cookie)
}
}