Commit 6e4eb637 authored by endk-mirror-svc's avatar endk-mirror-svc

Initial commit

parents
Copyright (c) 2018 The go-eds Mads R. Havmand. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
go-eds is a Go client library for accessing the energidataservice.dk API
go-eds internal structure is heavily inspired by Google's [go-github](https://github.com/google/go-github)
# License
This library is distributed under the BSD-style license found in the LICENSE file.
package eds
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
const (
defaultBaseURL = "https://api.energidataservice.dk/"
userAgent = "go-eds"
)
// Client is the object used to query the Energi Data Service API.
type Client struct {
client *http.Client // HTTP client used to communicate with the EDS API
BaseURL *url.URL // Base URL for API requests. Defaults to the public for
// EDS.
UserAgent string // User agent used when communicating with the EDS API.
common service // Reuse a single struct instead of allocating one for each service on the heap.
// Services used for talking to different parts of the EDS API
// Package *PackageService
}
type service struct {
client *Client
}
// NewClient returns a new EDS API client. If a nil httpClient is
// provided, http.DefaultClient will be used.
func NewClient(httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
baseURL, _ := url.Parse(defaultBaseURL)
c := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent}
c.common.client = c
// c.Package = (*PackageService)(&c.common)
return c
}
// NewRequest creates an API request. A relative URL can be provided in urlStr,
// in which case it is resolved relative to the BaseURL of the Client.
// Relative URLs should always be specified without a preceding slash. If
// specified, the value pointed to by body is JSON encoded and included as the
// request body.
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
if !strings.HasSuffix(c.BaseURL.Path, "/") {
return nil, fmt.Errorf("BaseURL must have a trailing slash, but %q does not", c.BaseURL)
}
u, err := c.BaseURL.Parse(urlStr)
if err != nil {
return nil, err
}
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
err := enc.Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.UserAgent != "" {
req.Header.Set("User-Agent", c.UserAgent)
}
return req, nil
}
// Do sends and API request and returns the API response. The API response is
// JSON decoded and stored in the value pointed to by v, or returned as an
// error if an API error has occurred. If v implements the io.Writer
// interface, the raw response body will be written to v, without attempting to
// first decode it.
//
// The provided ctx must be non-nil. If it is canceled or times out,
// ctx.Err() will be returned.
func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*http.Response, error) {
req = req.WithContext(ctx)
resp, err := c.client.Do(req)
if err != nil {
// If we got an error, and the context has been canceled,
// the context's error is probably more useful.
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
return nil, err
}
defer resp.Body.Close()
if v != nil {
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
} else {
decErr := json.NewDecoder(resp.Body).Decode(v)
if decErr == io.EOF {
decErr = nil // ignore EOF errors caused by empty response body
}
if decErr != nil {
err = decErr
}
}
}
return resp, err
}
//type response struct {
// Help string `json:"help"`
// Success bool `json:"success"`
// Result []string `json:"result"`
//}
//
//// ListPackages returns a list of packages from Energi Data Service.
////
//// The limit may be set to 0 to get all packages.
//func (c *Client) ListPackages(limit int, offset int) ([]string, error) {
// if c.BaseURL == nil {
// u, err := url.Parse(DefaultURL)
// if err != nil {
// return nil, err
// }
// c.BaseURL = u
// }
// if c.httpClient == nil {
// c.httpClient = http.DefaultClient
// }
//
// rel := &url.URL{Path: "/package_list"}
// u := c.BaseURL.ResolveReference(rel)
//
// query := u.Query()
// query.Add("limit", string(limit))
// query.Add("offset", string(offset))
// u.RawQuery = query.Encode()
//
// req, err := http.NewRequest("GET", u.String(), nil)
// if err != nil {
// return nil, err
// }
// req.Header.Set("Accept", "application/json")
// req.Header.Set("User-Agent", c.UserAgent)
//
// resp, err := c.httpClient.Do(req)
// if err != nil {
// return nil, err
// }
// defer resp.Body.Close()
// var apiResponse response
// err = json.NewDecoder(resp.Body).Decode(&apiResponse)
// return apiResponse.Result, err
//}
package eds_test
import (
"net/url"
"testing"
eds "gitlab.com/MadsRC/go-eds"
)
//func TestListPackages(t *testing.T) {
// ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// w.Header().Set("Content-Type", "application/json")
// fmt.Fprintln(w, `{"help": "https://api.energidataservice.dk/help_show?name=package_list", "success": true, "result": ["afrrreservesdk1", "capacityauctiondk1", "capacityauctiondk2", "co2emis", "co2emisprog", "communityconsumption", "communityproduction", "electricitybalance", "electricitybalancenonv", "electricityprodex5minrealtime", "elspotprices", "entryexitgasquality", "fcrreservesdk1", "fcrreservesdk2", "fixedresidualconsumption", "gascomposition", "mfrrreservesdk1", "mfrrreservesdk2", "mrstationsgasquality", "nordpoolmarket", "realtimemarket", "storagecapacity", "transmissionlines"]}`)
// }))
// defer ts.Close()
// tURL, err := url.Parse(ts.URL)
// if err != nil {
// t.Error(err)
// }
// eds := edsgo.Client{
// BaseURL: tURL,
// }
// e, err := eds.ListPackages(0, 0)
// if err != nil {
// t.Error(err)
// }
// t.Log(e)
//}
const ()
func TestNewClient(t *testing.T) {
_ = eds.NewClient(nil)
}
func TestNewRequest(t *testing.T) {
tests := []struct {
method string
urlStr string
body interface{}
baseURL string
userAgent string
fail bool
}{
{"GET", "", "", "https://api.energidataservice.dk", "", true},
{"GET", "\\htp:/thisiswrong.dk", "", "https://api.energidataservice.dk/", "", true},
{"GET", "package_list", "", "", "custom user-agent 2.0", false},
{"GET", "package_list", "", "", "", false},
}
for i, test := range tests {
c := eds.NewClient(nil)
if test.baseURL != "" {
c.BaseURL, _ = url.Parse(test.baseURL)
}
if test.userAgent != "" {
c.UserAgent = test.userAgent
}
_, err := c.NewRequest(test.method, test.urlStr, test.body)
if test.fail {
if err == nil {
t.Errorf("Test failed at iteration %d with nil error\n", i)
}
} else {
if err != nil {
t.Errorf("Test failed at iteration %d with error: %v\n", i, err)
}
}
}
}
func TestDo(t *testing.T) {
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment