Skip to content

Commit

Permalink
Merge pull request #1 from Piszmog/develop
Browse files Browse the repository at this point in the history
Release 1.0.0
  • Loading branch information
Piszmog committed Aug 12, 2018
2 parents 1274978 + d126642 commit 81adc8e
Show file tree
Hide file tree
Showing 27 changed files with 1,008 additions and 229 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,3 @@
*.ipr

/vendor
go.sum
33 changes: 33 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
language: go

go:
- "1.10"

notifications:
email:
on_success: never
on_failure: always

matrix:
# It's ok if our code fails on unstable development versions of Go.
allow_failures:
- go: develop
# Don't wait for tip tests to finish. Mark the test run green if the
# tests pass on the stable versions of Go.
fast_finish: true
cache:
directories:
- $GOPATH/pkg
- $GOPATH/bin

before_install:
- go get -u golang.org/x/vgo
- go get golang.org/x/tools/cmd/cover
- go get github.com/mattn/goveralls

install:
- vgo mod vendor

script:
- go test -v ./... -covermode=count -coverprofile=coverage.out
- $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci
46 changes: 46 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [email protected]. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]

[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
10 changes: 10 additions & 0 deletions ISSUE_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
### Issue Description


### Steps to Reproduce


### Expected Behavior


### Acceptance Criteria
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) 2018 Piszmog

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.
10 changes: 10 additions & 0 deletions PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
### Changes Description


### Associated Issues


### Affected Files


### Unit Tests Changed or Added
80 changes: 78 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Go Config Server Client
[![Build Status](https://travis-ci.org/Piszmog/cloudconfigclient.svg?branch=develop)](https://travis-ci.org/Piszmog/cloudconfigclient)
[![Coverage Status](https://coveralls.io/repos/github/Piszmog/cloudconfigclient/badge.svg?branch=develop)](https://coveralls.io/github/Piszmog/cloudconfigclient?branch=develop)
[![Go Report Card](https://goreportcard.com/badge/github.com/Piszmog/cloudconfigclient)](https://goreportcard.com/report/github.com/Piszmog/cloudconfigclient)
[![GitHub release](https://img.shields.io/github/release/Piszmog/cloudconfigclient.svg)](https://github.com/Piszmog/cloudconfigclient/releases/latest)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Go library for Spring Config Server. Inspired by the Java library [Cloud Config Client](https://github.com/Piszmog/cloud-config-client)

Expand All @@ -10,6 +14,65 @@ can be used to load the base configurations an application requires to function.

This library provides clients the ability to load Configurations and Files from the Config Server

## Example Usage
Below is an example usage of the library to retrieve a file from the Config Server and to retrieve the application's configurations

* For local config client, ensure `CONFIG_SERVER_URLS` is set
* `CONFIG_SERVER_URLS` is a comma separated list of all the base URLs
* For running in Cloud Foundry, ensure a Config Server is bounded to the application. `VCAP_SERVICES` will be provided as an environment variables with the credentials to access the Config Server
* If not running in Cloud Foundry but still want to connect to a Config Server via OAuth2, manually set the `VCAP_SERVICES` -- example value in `client/oauth2_test.go`

```go
package main

import (
"fmt"
"github.com/Piszmog/cloudconfigclient/client"
)

type File struct {
Example Example `json:"example"`
}

type Example struct {
Field string `json:"field"`
}

func main() {
// To create a Client for a locally running Spring Config Server
configClient, err := client.CreateLocalClient()
// or to create a Client for a Spring Config Server in Cloud Foundry
configClient, err := client.CreateCloudClient()
if err != nil {
panic(err)
}
var file File
// Retrieves a 'temp1.json' from the Config Server's default branch in directory 'temp' and deserialize to File
err = configClient.GetFile("temp", "temp1.json", &file)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", file)

// Retrieves the configurations from the Config Server based on the application name and active profiles
config, err := configClient.GetConfiguration("testApp", []string{"dev"})
if err != nil {
panic(err)
}
fmt.Printf("%+v", config)
}
```

## Config Client Creation
There are two type of clients that can be created. A local client for a locally running Config Server without security (OAuth2)
and a cloud client for a Config Server running in a cloud environment.

### Local
To create a local client, call `client.CreateLocalClient()`. The client is configured with timeouts set and to use a pool of connections.

### Cloud
To create a cloud client, call `client.CreateCloudClient()`. The client is an OAuth2 client. The OAuth2 configurations are determined from the `VCAP_SERVICES` environment variable.

## Configurations
The Config Server allows the ability to retrieve configurations for an application. Only files that follow a strict naming
convention will be loaded,
Expand Down Expand Up @@ -43,8 +106,21 @@ The loaded configurations are in the following JSON format,
}
```

To use the library to retrieve configurations, use a client of `configuration.Configuration` called `configuration.Client` and
To use the library to retrieve configurations, create a `client/ConfigClient` and
invoke the method `GetConfiguration(applicationName string, profiles []string)`. The return will be the struct representation
of the configuration JSON - `model.Configuration`.

## Resources
## Resources
Spring's Config Server allows two ways to retrieve files from a backing repository.

| URL Path |
| :---: |
|`/<appName>/<profiles>/<directory>/<file>?useDefaultLabel=true`|
|`/<appName>/<profiles>/<branch>/<directory>/<file>?useDefaultLabel=true`|

* When retrieving a file from the Config Server's default branch, the file must not exist at the root of the repository.

The functions available to retrieve resource files are, `GetFile(directory string, file string, interfaceType interface{}) error` and
`GetFileFromBranch(branch string, directory string, file string, interfaceType interface{})`.

* The `interfaceTypee` is the object to deserialize the file to
30 changes: 30 additions & 0 deletions client/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package client

import (
"github.com/Piszmog/cloudconfigclient/net"
"github.com/pkg/errors"
"net/http"
)

// ConfigClient contains the clients of the Config Servers.
type ConfigClient struct {
Clients []CloudClient
}

// CloudClient interacts with the Config Server's REST APIs
type CloudClient interface {
Get(uriVariables ...string) (resp *http.Response, err error)
}

// Client that wraps http.Client and the base Uri of the http client
type Client struct {
configUri string
httpClient *http.Client
}

// Get performs a REST GET
func (client Client) Get(uriVariables ...string) (resp *http.Response, err error) {
fullUrl := net.CreateUrl(client.configUri, uriVariables...)
response, err := client.httpClient.Get(fullUrl)
return response, errors.Wrapf(err, "failed to retrieve from %s", fullUrl)
}
72 changes: 72 additions & 0 deletions client/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package client

import (
"bytes"
"io/ioutil"
"net/http"
"testing"
)

type mockCloudClient struct {
code int
response string
error error
}

func (client mockCloudClient) Get(uriVariables ...string) (resp *http.Response, err error) {
if client.error != nil {
return nil, client.error
}
return &http.Response{
StatusCode: client.code,
// Send response to be tested
Body: ioutil.NopCloser(bytes.NewBufferString(client.response)),
// Must be set to non-nil value or it panics
Header: make(http.Header),
}, nil
}

func createMockConfigClient(code int, response string, err error) *ConfigClient {
client := mockCloudClient{code: code, response: response, error: err}
return &ConfigClient{Clients: []CloudClient{client}}
}

type RoundTripFunc func(req *http.Request) *http.Response

func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}

func createMockHttpClient(fn RoundTripFunc) *http.Client {
return &http.Client{
Transport: RoundTripFunc(fn),
}
}

func TestClient_Get(t *testing.T) {
httpClient := createMockHttpClient(func(req *http.Request) *http.Response {
return &http.Response{
StatusCode: 200,
// Send response to be tested
Body: ioutil.NopCloser(bytes.NewBufferString(`OK`)),
// Must be set to non-nil value or it panics
Header: make(http.Header),
}
})
client := &Client{
configUri: "http://localhost:8080",
httpClient: httpClient,
}
resp, err := client.Get("some", "path")
if err != nil {
t.Errorf("failed to call the mock server with error %v", err)
}
if resp == nil {
t.Errorf("expected a response body")
}
defer resp.Body.Close()
byteBody, _ := ioutil.ReadAll(resp.Body)
if string(byteBody) != "OK" {
t.Error("failed to read body")
}
}
56 changes: 56 additions & 0 deletions client/configuration.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package client

import (
"encoding/json"
"github.com/Piszmog/cloudconfigclient/net"
"github.com/pkg/errors"
)

// Source is the application's source configurations. It con contain zero to n number of property sources.
type Source struct {
Name string `json:"name"`
Profiles []string `json:"profiles"`
Label string `json:"label"`
Version string `json:"version"`
State string `json:"state"`
PropertySources []PropertySource `json:"propertySources"`
}

// PropertySource is the property source for the application.
//
// A property source is either a YAML or a PROPERTIES file located in the repository that a Config Server is pointed at.
type PropertySource struct {
Name string `json:"name"`
Source map[string]interface{} `json:"source"`
}

// Configuration interface for retrieving an application's configuration files from the Config Server.
type Configuration interface {
GetConfiguration(applicationName string, profiles []string) (*Source, error)
}

// GetConfiguration retrieves the configurations/property sources of an application based on the name of the application
// and the profiles of the application.
func (configClient ConfigClient) GetConfiguration(applicationName string, profiles []string) (*Source, error) {
for _, client := range configClient.Clients {
resp, err := client.Get(applicationName, net.JoinProfiles(profiles))
if resp != nil && resp.StatusCode == 404 {
continue
}
if err != nil {
return nil, errors.Wrapf(err, "failed to retrieve application configurations")
}
if resp.StatusCode != 200 {
return nil, errors.Errorf("server responded with status code %d", resp.StatusCode)
}
configuration := &Source{}
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(configuration)
resp.Body.Close()
if err != nil {
return nil, errors.Wrapf(err, "failed to decode response from url")
}
return configuration, nil
}
return nil, errors.Errorf("failed to find configuration for application %s with profiles %s", applicationName, profiles)
}
Loading

0 comments on commit 81adc8e

Please sign in to comment.