added bridge to main

This commit is contained in:
Wlad Meixner 2019-02-09 17:10:11 +01:00
parent d336ec74ac
commit 41a3c0ba41
3 changed files with 61 additions and 17 deletions

View File

@ -3,6 +3,8 @@ package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
)
@ -11,6 +13,13 @@ type Bridge struct {
Config *Config
}
// NewBridge creates a new bridge api instance
func NewBridge(conf *Config) *Bridge {
return &Bridge{
Config: conf,
}
}
func (b *Bridge) postToBridge(endpoint string, payload interface{}) (interface{}, error) {
data, errMarhshal := json.Marshal(payload)
if errMarhshal != nil {
@ -31,6 +40,34 @@ func (b *Bridge) postToBridge(endpoint string, payload interface{}) (interface{}
return res, nil
}
func (b *Bridge) getFromBridge(endpoint string, target interface{}) error {
uri := b.getBridgeAPIURI() + endpoint
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
return err
}
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
return errors.New("Mite responded with error" + res.Status + fmt.Sprint(res.StatusCode))
}
// Unmarshal data
errDecode := json.NewDecoder(res.Body).Decode(target)
if errDecode != nil {
return err
}
return nil
}
func (b *Bridge) getBridgeAPIURI() string {
return b.Config.BridgeAddrScheme + "://" + b.Config.BridgeAddr + "/api/" + b.Config.Username
}

View File

@ -2,7 +2,7 @@ package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
@ -20,22 +20,21 @@ func (c *Config) createNewUser() {
// TODO: read/create the url
url := "http://192.168.178.46/api"
var reqBody = []byte(`{"devicetype": "go-hue-interface#Philips hue"}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBody))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
var reqBody = []byte(`{"devicetype": "go-hue-interface#Philips hue"}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBody))
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
json.Unmarshal([]byte(str), &res)
fmt.Println(res)
fmt.Println(res.Fruits[0])
// json.Unmarshal([]byte(str), &resp)
fmt.Println(resp)
}

10
main.go
View File

@ -8,4 +8,12 @@ const VERSION = "0.1.2"
func main() {
fmt.Printf("go-hue-interface v. %s \n", VERSION)
}
config := &Config{
Username: "nX1ye7AMQoQswiiJdxyw-92-RNhIwicXiQRg7AtF",
}
bridge := NewBridge(config)
fmt.Println("Created bridge ", bridge)
}