Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
radulucut committed Nov 8, 2023
0 parents commit f38c6b9
Show file tree
Hide file tree
Showing 13 changed files with 1,489 additions and 0 deletions.
20 changes: 20 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: Test

on: [push]

jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
go: ["1.16"]
os: [ubuntu-latest]
name: ${{ matrix.os }} Go ${{ matrix.go }} Tests
steps:
- uses: actions/checkout@v3
- name: Setup go
uses: actions/setup-go@v3
with:
go-version: ${{ matrix.go }}
- run: go test
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Radu Lucut

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
58 changes: 58 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# coleteonline

Go (golang) client library for accessing the [Colete Online API](https://docs.api.colete-online.ro/).

[![Go Reference](https://pkg.go.dev/badge/github.com/radulucut/coleteonline.svg)](https://pkg.go.dev/github.com/radulucut/coleteonline)
![Test](https://github.com/radulucut/coleteonline/actions/workflows/test.yml/badge.svg)

## Install

`go get github.com/radulucut/coleteonline`

## Endpoints

- [] /search/country/{needle}
- [] /search/location/{countryCode}/{needle}
- [] /search/city/{countryCode}/{county}/{needle}
- [] /search/street/{countryCode}/{city}/{county}/{needle}
- [] /search/postal-code/{countryCode}/{city}/{county}/{street}
- [] /search/validate-postal-code/{countryCode}/{city}/{county}/{street}/{postalCode}
- [] /search/postal-code-reverse/{countryCode}/{postalCode}
- [x] /address
- [x] /service/list
- [x] /order
- [x] /order/price
- [x] /order/status/{uniqueId}
- [] /order/awb/{uniqueId}
- [x] /user/balance

## Usage

```go
package main

import (
"fmt"
"log"
"time"

"github.com/radulucut/coleteonline"
)

func main() {
client := coleteonline.NewClient(coleteonline.Config{
ClientId: "<ClientId>",
ClientSecret: "<ClientSecret>",
UseProduction: true,
Timeout: 10 * time.Second,
})
order := &coleteonline.Order{
// ...
}
res, err := client.CreateOrder(order)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", res)
}
```
51 changes: 51 additions & 0 deletions address.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package coleteonline

type Contact struct {
Name string `json:"name,omitempty"`
Phone string `json:"phone,omitempty"`
Phone2 string `json:"phone2,omitempty"`
Company string `json:"company,omitempty"`
Email string `json:"email,omitempty"`
}

type Address struct {
CountryCode string `json:"countryCode"`
PostalCode string `json:"postalCode"`
City string `json:"city"`
County string `json:"county"`
CountyCode string `json:"countyCode"`
Street string `json:"street"`
Number string `json:"number"`
Building string `json:"building,omitempty"`
Entrance string `json:"entrance,omitempty"`
Intercom string `json:"intercom,omitempty"`
Floor string `json:"floor,omitempty"`
Apartment string `json:"apartment,omitempty"`
Landmark string `json:"landmark,omitempty"`
AdditionalInfo string `json:"additionalInfo,omitempty"`
}

type ValidationStrategyType string

const (
ValidationStrategyTypeMinimal ValidationStrategyType = "minimal"
ValidationStrategyTypePriceMinimal ValidationStrategyType = "priceMinimal"
)

type OrderAddress struct {
AddressId int64 `json:"addressId"`
Contact Contact `json:"contact"`
Address Address `json:"address"`
ValidationStrategy ValidationStrategyType `json:"validationStrategy"`
}

type Pagination struct {
TotalItems int64 `json:"totalItems"`
CurrentPage int64 `json:"currentPage"`
TotalPages int64 `json:"totalPages"`
}

type AddressListResponse struct {
Data []OrderAddress `json:"data"`
Pagination Pagination `json:"pagination"`
}
7 changes: 7 additions & 0 deletions auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package coleteonline

type AuthToken struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
}
237 changes: 237 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
package coleteonline

import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
)

// https://docs.api.colete-online.ro
type Client struct {
authURL string
apiURL string
authBasic string
authBearer string
authBearerExp time.Time
http *http.Client
mu sync.Mutex
timeNow func() time.Time
}

type Config struct {
ClientId string
ClientSecret string
UseProduction bool
Timeout time.Duration
}

func NewClient(config Config) *Client {
client := &Client{
authURL: "https://auth.colete-online.ro/token",
authBasic: "Basic " + base64.StdEncoding.EncodeToString(
[]byte(config.ClientId+":"+config.ClientSecret),
),
http: &http.Client{
Timeout: config.Timeout,
},
timeNow: func() time.Time {
return time.Now()
},
mu: sync.Mutex{},
}
if config.UseProduction {
client.apiURL = "https://api.colete-online.ro/v1"
} else {
client.apiURL = "https://api.colete-online.ro/v1/staging"
}
return client
}

func (c *Client) GetAuthBearer() (*string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.timeNow().After(c.authBearerExp) {
req, err := http.NewRequest(
"POST",
c.authURL,
strings.NewReader("grant_type=client_credentials"),
)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", c.authBasic)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
r, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer r.Body.Close()
b, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // 1MB
if err != nil {
return nil, err
}
if r.StatusCode != 200 {
var rErr AuthResponseError
err = json.Unmarshal(b, &rErr)
if err != nil {
return nil, err
}
return nil, &rErr
}
var res AuthToken
err = json.Unmarshal(b, &res)
if err != nil {
return nil, err
}
c.authBearerExp, err = c.getExpiresAtFromJWT(res.AccessToken)
if err != nil {
return nil, err
}
c.authBearer = "Bearer " + res.AccessToken
}
return &c.authBearer, nil
}

func (c *Client) CreateOrder(order *Order) (*OrderResponse, error) {
var res OrderResponse
err := c.request("POST", "/order", order, &res)
if err != nil {
return nil, err
}
return &res, nil
}

func (c *Client) OrderPrice(order *Order) (*OrderPriceResponse, error) {
var res OrderPriceResponse
err := c.request("POST", "/order/price", order, &res)
if err != nil {
return nil, err
}
return &res, nil
}

func (c *Client) OrderStatus(uniqueIdOrAWB *string) (*OrderStatusResponse, error) {
var res OrderStatusResponse
err := c.request("GET", "/order/status/"+*uniqueIdOrAWB, nil, &res)
if err != nil {
return nil, err
}
return &res, nil
}

func (c *Client) AddressList(page int64) (*AddressListResponse, error) {
var res AddressListResponse
err := c.request("GET", fmt.Sprintf("/address?page=%d", page), nil, &res)
if err != nil {
return nil, err
}
return &res, nil
}

func (c *Client) ServiceList() ([]ServiceResponse, error) {
var res []ServiceResponse
err := c.request("GET", "/service", nil, &res)
if err != nil {
return nil, err
}
return res, nil
}

func (c *Client) UserBalance() (*UserBalance, error) {
var res UserBalance
err := c.request("GET", "/user/balance", nil, &res)
if err != nil {
return nil, err
}
return &res, nil
}

func (c *Client) request(
method string,
path string,
body interface{},
res interface{},
) error {
token, err := c.GetAuthBearer()
if err != nil {
return err
}
var b []byte
if body != nil {
b, err = json.Marshal(body)
if err != nil {
return err
}
}
req, err := http.NewRequest(
method,
c.apiURL+path,
bytes.NewReader(b),
)
if err != nil {
return err
}
req.Header.Set("Authorization", *token)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
r, err := c.http.Do(req)
if err != nil {
return err
}
defer r.Body.Close()
if r.StatusCode == 200 || r.StatusCode == 400 {
b, err = io.ReadAll(io.LimitReader(r.Body, 1<<20)) // 1MB
if err != nil {
return err
}
if r.StatusCode == 400 {
var rErr ResponseError
err = json.Unmarshal(b, &rErr)
if err != nil {
return err
}
return &rErr
}
err = json.Unmarshal(b, res)
if err != nil {
return err
}
return nil
}
if r.StatusCode == 401 {
c.authBearer = ""
return c.request(method, path, body, res)
}
return &ResponseError{
Message: "unexpected response status",
Code: r.StatusCode,
}
}

// This does not guarantee that the token/payload is valid.
func (c *Client) getExpiresAtFromJWT(token string) (time.Time, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return time.Time{}, errors.New("invalid JWT token")
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return time.Time{}, err
}
var claims struct {
Exp int64 `json:"exp"`
}
err = json.Unmarshal(payload, &claims)
if err != nil {
return time.Time{}, fmt.Errorf("invalid JWT payload: %s", err)
}
return time.Unix(claims.Exp, 0), nil
}
Loading

0 comments on commit f38c6b9

Please sign in to comment.