Skip to content

Commit 3147596

Browse files
authored
Support basic authorization (#149)
1 parent f45abfe commit 3147596

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,10 @@ uri: https://volkszaehler/api/data/<uuid>.json?from=now
419419
method: GET # default HTTP method
420420
headers:
421421
- content-type: application/json
422+
auth: # basic authorization
423+
type: basic
424+
user: foo
425+
password: bar
422426
insecure: false # set to true to trust self-signed certificates
423427
jq: .data.tuples[0][1] # parse response json
424428
scale: 0.001 # floating point factor applied to result, e.g. for kW to W conversion

provider/http.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package provider
22

33
import (
44
"crypto/tls"
5+
"encoding/base64"
56
"fmt"
67
"io"
78
"math"
@@ -25,6 +26,21 @@ type HTTP struct {
2526
jq *gojq.Query
2627
}
2728

29+
// Auth is the authorization config
30+
type Auth struct {
31+
Type, User, Password string
32+
}
33+
34+
// NewAuth creates authorization headers from config
35+
func NewAuth(log *util.Logger, auth Auth, headers map[string]string) {
36+
if strings.ToLower(auth.Type) != "basic" {
37+
log.FATAL.Fatalf("config: unsupported auth type: %s", auth.Type)
38+
}
39+
40+
basicAuth := auth.User + ":" + auth.Password
41+
headers["Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(basicAuth))
42+
}
43+
2844
// NewHTTPProviderFromConfig creates a HTTP provider
2945
func NewHTTPProviderFromConfig(log *util.Logger, other map[string]interface{}) *HTTP {
3046
cc := struct {
@@ -34,6 +50,7 @@ func NewHTTPProviderFromConfig(log *util.Logger, other map[string]interface{}) *
3450
Jq string
3551
Scale float64
3652
Insecure bool
53+
Auth Auth
3754
}{}
3855
util.DecodeOther(log, other, &cc)
3956

@@ -49,6 +66,14 @@ func NewHTTPProviderFromConfig(log *util.Logger, other map[string]interface{}) *
4966
scale: cc.Scale,
5067
}
5168

69+
// handle basic auth
70+
if cc.Auth.Type != "" {
71+
if p.headers == nil {
72+
p.headers = make(map[string]string)
73+
}
74+
NewAuth(log, cc.Auth, p.headers)
75+
}
76+
5277
// ignore the self signed certificate
5378
if cc.Insecure {
5479
customTransport := http.DefaultTransport.(*http.Transport).Clone()

0 commit comments

Comments
 (0)