~bigbes/core-go

ref: dd20891a281159b6bd6ecb5f3cd2514411a79619 core-go/client/graphql.go -rw-r--r-- 1.7 KiB
dd20891a — Julien Moutinho Replace x/crypto package by ProtonMail/go-crypto to support ed25519 OpenPGP keys 4 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package client

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"git.sr.ht/~sircmpwn/core-go/config"
	"git.sr.ht/~sircmpwn/core-go/crypto"
)

type GraphQLQuery struct {
	Query     string                 `json:"query"`
	Variables map[string]interface{} `json:"variables"`
}

type InternalAuth struct {
	Name     string `json:"name"`
	ClientID string `json:"client_id"`
	NodeID   string `json:"node_id"`
}

func Execute(ctx context.Context, username string, svc string,
	query GraphQLQuery, result interface{}) error {
	body, err := json.Marshal(query)
	if err != nil {
		panic(err) // Programmer error
	}

	conf := config.ForContext(ctx)
	origin, _ := conf.Get(svc, "api-origin")
	if origin == "" {
		origin = config.GetOrigin(conf, svc, false)
	}
	if origin == "" {
		panic(fmt.Errorf("No %s origin specified in config.ini", svc))
	}

	reader := bytes.NewBuffer(body)
	req, err := http.NewRequestWithContext(ctx,
		"POST", fmt.Sprintf("%s/query", origin), reader)
	if err != nil {
		return err
	}
	req.Header.Add("Content-Type", "application/json")
	auth := InternalAuth{
		Name:     username,
		ClientID: config.ServiceName(ctx),
		// TODO: Populate this:
		NodeID: "core-go",
	}
	authBlob, err := json.Marshal(&auth)
	if err != nil {
		panic(err) // Programmer error
	}
	req.Header.Add("Authorization", fmt.Sprintf("Internal %s",
		crypto.Encrypt(authBlob)))
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}

	defer resp.Body.Close()
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	if resp.StatusCode != 200 {
		return fmt.Errorf("%s returned status %d: %s",
			svc, resp.StatusCode, string(respBody))
	}

	if err = json.Unmarshal(respBody, result); err != nil {
		return err
	}

	return nil
}