You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
2.0 KiB
Go
75 lines
2.0 KiB
Go
package mobilizon
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
"net/http"
|
|
"net/url"
|
|
|
|
gql "github.com/hasura/go-graphql-client"
|
|
)
|
|
|
|
type MobilizonClient struct {
|
|
client *gql.Client
|
|
httpClient *http.Client
|
|
url string
|
|
refreshToken String
|
|
}
|
|
|
|
func NewMobilizonClient(host string) *MobilizonClient {
|
|
u, _ := url.Parse(host)
|
|
u.Path = "api"
|
|
httpClient := http.DefaultClient
|
|
return &MobilizonClient{
|
|
httpClient: httpClient,
|
|
client: gql.NewClient(u.String(), httpClient),
|
|
url: u.String(),
|
|
}
|
|
}
|
|
|
|
// makeMultipartRequest is used for file upload. This is enabled in Mobilizon
|
|
// through multipart/form-data request bodies, with at least 3 fields:
|
|
// - query: the raw graphql mutation string
|
|
// - variables: a json encoded object with variables. variables of type `Upload` contain the key to the
|
|
// file content in the files map
|
|
// - files: a name-content mapping of files, referenced by the variable values of type Upload
|
|
func (c MobilizonClient) makeMultipartRequest(query string, variables map[string]interface{}, files map[string]io.Reader) (*http.Request, error) {
|
|
body := new(bytes.Buffer)
|
|
mp := multipart.NewWriter(body)
|
|
// for some reason, mobilizon does not accept the default delimiters...
|
|
const multipartDelim = "---------------------------164507724316293925132493775707"
|
|
mp.SetBoundary(multipartDelim)
|
|
|
|
vars, err := json.Marshal(variables)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
mp.WriteField("variables", string(vars)) // json encoded
|
|
mp.WriteField("query", query) // raw string
|
|
|
|
// file parts must be named the same as the variable value they map to
|
|
for name, content := range files {
|
|
filePart, err := mp.CreateFormFile(name, name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
_, err = io.Copy(filePart, content)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
mp.Close()
|
|
|
|
req, err := http.NewRequest("POST", c.url, body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
req.Header.Add("Content-Type", fmt.Sprintf("multipart/form-data; boundary=%s", multipartDelim))
|
|
|
|
return req, nil
|
|
}
|