cosmos_db_restapi

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2022 License: MIT Imports: 15 Imported by: 0

README

golang_cosmos_db_restapi

golang sql api for cosmos db

go get github.com/jankstar/golang_cosmos_db_restapi

Prerequisites

go version 1.18+

Function

GetAuthorizationTokenUsingMasterKey

GetAuthorizationTokenUsingMasterKey function for generating access token https://docs.microsoft.com/en-us/rest/api/cosmos-db/access-control-on-cosmosdb-resources

Parameters:
Verb: "GET"
Ressourcentyp: "dbs"
Resource Linkage: "dbs/ToDoList"
Date: "Thu, 27 Apr 2017 00:51:12 GMT"
masterKey: "dsZQi3KtZmCv1ljt3VNWNm7sQUF1y5rJfC6kv5JiwvW0EndXdDku/dkKBp8/ufDToSxLzR4y+O/0H/t4bQtVNw=="
Return:
authorization: "typ%3dmaster%26ver%3d1.0%26sig%3dc09PEVJrgp2uQRkr934kFbTqhByc7TVr3OHyqlu%2bc%2bc%2bc%3d"

ExecuteQuerry

ExecuteQuerry - execute a query as rest api

https://docs.microsoft.com/en-us/rest/api/cosmos-db/querying-cosmosdb-resources-using-the-rest-api

Parameters:
endpoint_uri - uri from cosmos db
master_key - masker key from cosmos db
database - name of database
container - name of container
partitionkey - optional partition key else ""
max_item_count - optional max item count else 0
querry - like TQuerry
Returns:
Status - response status i.e. 200 ok
Body - response body as string
Continuation - the Continuation-token if there are more items to read

CreateDocument

CreateDocument - create or rewrite an object by ID via rest api

https://docs.microsoft.com/en-us/rest/api/cosmos-db/create-a-document

Parameters:
endpoint_uri - uri from cosmos db
master_key - master key from cosmos db
database - name of database
container - name of container
partitionkey - optional partition (if container defined with partion key, it is required)
upset -- optional boolean, true: create or update, if exist
data - json data as sting of the item
Returns:
Status - response status i.e. 201 Created
Body - response body as string

GetDocumentByID

GetDocumentByID - get an object by ID via rest api

https://docs.microsoft.com/en-us/rest/api/cosmos-db/get-a-document

Parameters:
endpoint_uri - uri from cosmos db
master_key - master key from cosmos db
database - name of database
container - name of container
partitionkey - optional partition (if container defined with partion key, it is required)
id - id of the item
Returns:
Status - response status i.e. 200 ok
Body - response body as string

DeleteDocumentByID

DeleteDocumentByID - delete an object by ID via rest api

https://docs.microsoft.com/en-us/rest/api/cosmos-db/delete-a-document

Parameters:
endpoint_uri - uri from cosmos db
master_key - master key from cosmos db
database - name of database
container - name of container
partitionkey - optional partition (if container defined with partion key, it is required)
id - id of the item
Returns:
Status - response status i.e. 204 No Content 
Body - response body as string i.e. ""

Example 1 - native operations

func test() {
	//get the "endpoint" and master-key from the .env file
	godotenv.Load(".env")
	endpoint := os.Getenv("ENDPOINT_URI")
	key := os.Getenv("MASTER_KEY")

	var querry = TQuerry{
		Query: "SELECT * FROM c WHERE c.word = @word1 OR c.word = @word2 ",
		Parameters: []TParameter{
			{
				Name:  "@word1",
				Value: "Zwerg",
			},
			{
				Name:  "@word2",
				Value: "Nase",
			}},
	}

	req_continuation := ""
	steps := 0
	for req_continuation != "" || steps == 0 {
		steps += 1
		fmt.Println("Step:", steps)

		res_status, res_body, res_continuation := ExecuteQuerry(
			endpoint, key,
			"lerneria-express", "dictionary", "", //no patition key
			3, req_continuation, //only 3 documents per request
			querry)
		fmt.Println("Status: " + res_status)
		//last "continuation" header becomes new request value
		req_continuation = res_continuation

		var MyBody TBody
		_ = json.Unmarshal([]byte(res_body), &MyBody)
		fmt.Println("Count: " + strconv.Itoa(int(MyBody.Count)))
		fmt.Println("continuation:", res_continuation)
		fmt.Println("Documents:")
		for _, doc := range MyBody.Documents {

			//mapping the interface{} element to struc
			type Dic struct {
				Etag      string `mapstructure:"_etag"`
				Rid       string `mapstructure:"_rid"`
				ID        string `mapstructure:"id"`
				Word      string `mapstructure:"word"`
				Snippet   string `mapstructure:"snippet"`
				CreatedAt string `mapstructure:"created_at"`
			}
			var MyDic Dic
			mapstructure.Decode(doc, &MyDic)

			fmt.Println(MyDic)
		}
	}

}

Example 2 - object-like operations

func test() {
	//get the "endpoint" and master-key from the .env file
	godotenv.Load(".env")
	endpoint := os.Getenv("ENDPOINT_URI")
	key := os.Getenv("MASTER_KEY")

	var querry = TQuerry{
		Query: "SELECT * FROM c WHERE c.word = @word1 OR c.word = @word2 ",
		Parameters: []TParameter{
			{
				Name:  "@word1",
				Value: "Zwerg",
			},
			{
				Name:  "@word2",
				Value: "Nase",
			}},
	}

	container := ContainerFactory(
		DatabaseFactory(
			endpoint,
			key,
			"lerneria-express"),
		"dictionary",
		"")

	container.OpenQuerry(3, querry) //set query for fetching with 3 docs

	for {
		res_status, res_body := container.Fetch() //fetching data
		fmt.Println("Status: " + res_status)
		if !strings.Contains(res_status, "200") || res_body == "" {
			break //Cancel because error
		}

		var MyBody TBody
		_ = json.Unmarshal([]byte(res_body), &MyBody)
		fmt.Println("Count: " + strconv.Itoa(int(MyBody.Count)))
		fmt.Println("continuation:", container.Continuation)
		fmt.Println("Documents:")
		for _, doc := range MyBody.Documents {

			//mapping the interface{} element to struc
			type Dic struct {
				Etag      string `mapstructure:"_etag"`
				Rid       string `mapstructure:"_rid"`
				ID        string `mapstructure:"id"`
				Word      string `mapstructure:"word"`
				Snippet   string `mapstructure:"snippet"`
				CreatedAt string `mapstructure:"created_at"`
			}
			var MyDic Dic
			mapstructure.Decode(doc, &MyDic)

			fmt.Println(MyDic)
		}
	}
}

Documentation

Overview

package cosmos_db_restapi Golang Package for the cosmos db rest api

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateDocument

func CreateDocument(endpoint_uri string, master_key string, database string, container string, partitionkey string, upset bool, data string) (Status string, Body string)

func DeleteDocumentByID

func DeleteDocumentByID(endpoint_uri string, master_key string, database string, container string, partitionkey string, id string) (Status string, Body string)

DeleteDocumentByID - delete an object by ID via rest api

parameters:

endpoint_uri - uri from cosmos db
master_key - master key from cosmos db
database - name of database
container - name of container
partitionkey - optional partition (if container defined with partion key, it is required)
id - id of the item

returns:

Status - response status i.e. 204 No Content
Body - response body as string i.e. ""

func ExecuteQuerry

func ExecuteQuerry(endpoint_uri string, master_key string, database string, container string, partitionkey string, max_item_count int, continuation string, query TQuerry) (Status string, Body string, Continuation string)

ExecuteQuerry - execute a query as rest api

parameters:

endpoint_uri - uri from cosmos db
master_key - master key from cosmos db
database - name of database
container - name of container
partitionkey - optional partition key else ""
max_item_count - optional max item count else 0
querry - like TQuerry

returns:

Status - response status i.e. 200 ok
Body - response body as string
Continuation - the Continuation-token if there are more items to read

func GetAuthorizationTokenUsingMasterKey

func GetAuthorizationTokenUsingMasterKey(
	verb string,
	resourceType string,
	resourceId string,
	date string,
	masterKey string) string

GetAuthorizationTokenUsingMasterKey function for generating access token

https://docs.microsoft.com/en-us/rest/api/cosmos-db/access-control-on-cosmosdb-resources

func GetDocumentByID

func GetDocumentByID(endpoint_uri string, master_key string, database string, container string, partitionkey string, id string) (Status string, Body string)

GetDocumentByID - get an object by ID via rest api

parameters:

endpoint_uri - uri from cosmos db
master_key - master key from cosmos db
database - name of database
container - name of container
partitionkey - optional partition (if container defined with partion key, it is required)
id - id of the item

returns:

Status - response status i.e. 200 ok
Body - response body as string

Types

type TBody

type TBody struct {
	Code      string        `json:"code"`      //error code from cosmos_db
	Message   string        `json:"message"`   //error message
	Rid       string        `json:"_rid"`      //resource ID
	Documents []interface{} `json:"Documents"` //array of data
	Count     uint          `json:"_count"`    //counts of documents
}

type TContainer added in v0.1.1

type TContainer struct {
	Database     TDatabase `json:"database"`
	Container    string    `json:"container"`
	PartitionKey string    `json:"partition_key"`
	Query        TQuerry   `json:"query"`
	MaxItemCount int       `json:"max_item_count"`
	Continuation string    `json:"continuation"`
	Steps        int       `json:"steps"`
	Status       string    `json:"status"`
	Body         string    `json:"body"`
}

TContainer - Object for accessing a container

func ContainerFactory added in v0.1.1

func ContainerFactory(database TDatabase, container string, partitionkey string) TContainer

ContainerFactory - creates a container object

func (*TContainer) CreateDocument added in v0.1.1

func (me *TContainer) CreateDocument(upset bool, data string) (Status string, Body string)

func (*TContainer) DeleteDocumentByID added in v0.1.1

func (me *TContainer) DeleteDocumentByID(id string) (Status string, Body string)

func (*TContainer) ExecuteQuerry added in v0.1.1

func (me *TContainer) ExecuteQuerry(max_item_count int, continuation string, query TQuerry) (Status string, Body string, Continuation string)

func (*TContainer) Fetch added in v0.1.1

func (me *TContainer) Fetch() (Status string, Body string)

Fetch - a fetch leads to a query

func (*TContainer) OpenQuerry added in v0.1.1

func (me *TContainer) OpenQuerry(max_item_count int, query TQuerry)

OpenQuerry - defines a query for execution in fetch mode

type TDatabase added in v0.1.1

type TDatabase struct {
	EndpointUri string `json:"endpoint_uri"`
	MasterKey   string `json:"master_key"`
	Database    string `json:"database"`
}

TDatabase - Structure for the access of the server and the database

func DatabaseFactory added in v0.1.1

func DatabaseFactory(endpoint_uri string, master_key string, database string) TDatabase

DatabaseFactory - creates a database object

type TParameter

type TParameter struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

TQuerry structure for querry call:

{
	"query":"SELECT * FROM c WHERE c.name = @name",
	"parameters": [{
		"name": "@name",
		"value": "Julian"
	}]
}

type TQuerry

type TQuerry struct {
	Query      string       `json:"query"`
	Parameters []TParameter `json:"parameters"`
}

Jump to

Keyboard shortcuts

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