brutella / hkknx-public

hkknx is a HomeKit KNX bridge for KNX.
https://hochgatterer.me/hkknx
97 stars 6 forks source link

POST requests in Script #160

Closed TobiasGeiselmann closed 2 years ago

TobiasGeiselmann commented 2 years ago

How are network requests supposed to be scripted? Using the standard golang functionality doesn't seem to work. I've already tried using http.Post from the net/http package, but that does not seem to be available. With http.PostForm I'm having trouble constructing the url.Values with the form data. Is there any script example that demonstrates this functionality?

matthafner commented 2 years ago

I am working on a video which uses this KNX bridge to connect to HomeKit and more (I played around a little to find out what this bridge is capable). Yes you are correct that there should be a little bit more examples of important things like this...

I had to figure out the same thing (so not sure this is the exact code which works for you but at least you can build of this ;) ). This is a GET request, I believe... but hope this is of help.

httpRequestExample

This is the response you get in hkknx:

httpRequestPrintln

This is the response you get in a browser for example:

httpRequestTeste

@brutella Hi, Matthias, did you receive my email regarding the video I want to make, I didn't hear back from you? Let me know if you would like to collaborate ;)

brutella commented 2 years ago

How are network requests supposed to be scripted? Using the standard golang functionality doesn't seem to work. I've already tried using http.Post from the net/http package, but that does not seem to be available.

Right, http.Post ist not available. Instead you have to use Post or PostForm function from the Client struct.

With http.PostForm I'm having trouble constructing the url.Values with the form data. Is there any script example that demonstrates this functionality?

This example is an adapted version from the net/http package documentation.

http = import("net/http")
url = import("net/url")

data = url.Values{"key": {"Value"}, "id": {"123"}}
client = &http.Client{}
resp, err = client.PostForm("http://example.com/form", data)

Ups. This example does not compile. 😬 See below for the correct answer.

TobiasGeiselmann commented 2 years ago

Thanks @brutella for your example. Unfortunately, I'm receiving a syntax error on the following line:

data = url.Values{"key": {"Value"}, "id": {"123"}}
brutella commented 2 years ago

Oh, sorry. This should work.

http = import("net/http")
url = import("net/url")

data = make(url.Values) 
data.Set("key", "Value")
data.Set("id", "123")

client = make(http.Client)
resp, err = client.PostForm("http://example.com/form", data)