opaclient

package module
v0.0.0-...-753efcf Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 7, 2021 License: MIT Imports: 9 Imported by: 0

README

OPA Go Client

Unofficial OPA HTTP Client in Go.

Usage

client, err := opaclient.New("http://localhost:8181")
if err != nil {
    panic(err)
}

req := opaclient.DataRequest{
    Path: "example/policy",
    Input: map[string]string{
        "user": "m-mizutani",
    },
}
resp := struct {
    Allowed bool `json:"allowed"`
}{}

if err := client.GetData(context.Background(), &req, &resp); err != nil {
    panic(err)
}

fmt.Println("allowed? =>", resp.Allowed)

Testing

Run OPA server with following command.

$ opa run -s ./testdata/policy/

Then, run go test

$ env OPA_BASE_URL=http://localhost:8181 go test -v .

License

MIT License

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidInput   = goerr.New("invalid input")
	ErrRequestFailed  = goerr.New("request to OPA server failed")
	ErrUnexpectedResp = goerr.New("unexpected response from OPA server")
)

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}
Example
package main

import (
	"context"
	"fmt"
	"os"
	"testing"

	opaclient "github.com/m-mizutani/opa-go-client"
	"github.com/stretchr/testify/require"
)

func main() {
	client, err := opaclient.New("http://localhost:8181")
	if err != nil {
		panic(err)
	}

	req := opaclient.DataRequest{
		Path: "example/policy",
		Input: map[string]string{
			"user": "m-mizutani",
		},
	}
	resp := struct {
		Allowed bool `json:"allowed"`
	}{}

	if err := client.GetData(context.Background(), &req, &resp); err != nil {
		panic(err)
	}

	fmt.Println("allowed? =>", resp.Allowed)
}

func setupClient(t *testing.T) *opaclient.Client {
	url, ok := os.LookupEnv("OPA_BASE_URL")
	if !ok {
		t.Skip("OPA_BASE_URL is not set")
	}

	client, err := opaclient.New(url)
	require.NoError(t, err)
	return client
}

func New

func New(baseURL string, options ...Option) (*Client, error)

func (*Client) GetData

func (x *Client) GetData(ctx context.Context, req *DataRequest, dst interface{}) error

func (*Client) ListPolicy

func (x *Client) ListPolicy(ctx context.Context) ([]*types.PolicyV1, error)

type DataRequest

type DataRequest struct {
	Input interface{}
	Path  string
}

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

type Option

type Option func(client *Client) error

func WithHTTPClient

func WithHTTPClient(httpClient HTTPClient) Option

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL