1
0
Fork 0
mirror of https://github.com/matrix-org/gomatrix synced 2025-12-19 04:38:03 +00:00

Add responses/room types. Add buildURL functions with examples

This commit is contained in:
Kegan Dougal 2016-11-30 11:46:33 +00:00
parent 97f4e98e1d
commit 527c6568c9
4 changed files with 160 additions and 4 deletions

View file

@ -1,8 +1,12 @@
// Package gomatrix implements the Matrix Client-Server API.
//
// Specification can be found at http://matrix.org/docs/spec/client_server/r0.2.0.html
package gomatrix
import (
"net/http"
"net/url"
"path"
"sync"
)
@ -20,11 +24,49 @@ type Client struct {
// TODO: Worker and Rooms
}
// BuildURL builds a URL with the Client's homserver/prefix/access_token set already.
func (cli *Client) BuildURL(urlPath ...string) string {
ps := []string{cli.Prefix}
for _, p := range urlPath {
ps = append(ps, p)
}
return cli.BuildBaseURL(ps...)
}
// BuildBaseURL builds a URL with the Client's homeserver/access_token set already. You must
// supply the prefix in the path.
func (cli *Client) BuildBaseURL(urlPath ...string) string {
// copy the URL. Purposefully ignore error as the input is from a valid URL already
hsURL, _ := url.Parse(cli.HomeserverURL.String())
parts := []string{hsURL.Path}
parts = append(parts, urlPath...)
hsURL.Path = path.Join(parts...)
query := hsURL.Query()
query.Set("access_token", cli.AccessToken)
hsURL.RawQuery = query.Encode()
return hsURL.String()
}
// BuildURLWithQuery builds a URL with query paramters in addition to the Client's homeserver/prefix/access_token set already.
func (cli *Client) BuildURLWithQuery(urlPath []string, urlQuery map[string]string) string {
u, _ := url.Parse(cli.BuildURL(urlPath...))
q := u.Query()
for k, v := range urlQuery {
q.Set(k, v)
}
u.RawQuery = q.Encode()
return u.String()
}
// NewClient creates a new Matrix Client ready for syncing
func NewClient(httpClient *http.Client, homeserverURL *url.URL, accessToken, userID string) *Client {
func NewClient(homeserverURL, userID, accessToken string) (*Client, error) {
hsURL, err := url.Parse(homeserverURL)
if err != nil {
return nil, err
}
cli := Client{
AccessToken: accessToken,
HomeserverURL: homeserverURL,
HomeserverURL: hsURL,
UserID: userID,
Prefix: "/_matrix/client/r0",
}
@ -36,7 +78,8 @@ func NewClient(httpClient *http.Client, homeserverURL *url.URL, accessToken, use
// "load" nothing. The client will work with this storer: it just won't remember the filter
// ID across restarts and hence request a new one. In practice, a database backend should be used.
cli.FilterStorer = NopFilterStore{}
cli.Client = httpClient
// By default, use the default HTTP client.
cli.Client = http.DefaultClient
return &cli
return &cli, nil
}