GO resty equivalent to the below CURL command - go

So, I have a curl command that works just fine. But, when I try to implement it in Resty I get an error: 405 (method not allowed). Now, that error code shouldn't be taken too seriously. Just an indication I am doing something wrong.
The curl command that works like a champ does this:
christianb#christianb-mac hashicorp % curl -vn --location --request PUT 'http://localhost:8081/artifactory/example-repo-local/crash.zip' \
--header 'Content-Type: application/zip' \
--data-binary '#./samples/crash.zip'
* Trying 127.0.0.1:8081...
* Connected to localhost (127.0.0.1) port 8081 (#0)
* Server auth using Basic with user 'admin'
> PUT /artifactory/example-repo-local/crash.zip HTTP/1.1
> Host: localhost:8081
> Authorization: Basic xxx=
> User-Agent: curl/7.78.0
> Accept: */*
> Content-Type: application/zip
> Content-Length: 0
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 201
< X-JFrog-Version: Artifactory/7.24.3 72403900
< X-Artifactory-Id: 65b0c15e32af425b:-53411fa9:17be4f9b6e8:-8000
< X-Artifactory-Node-Id: cb4b887aed9e
< Location: http://localhost:8081/artifactory/example-repo-local/crash.zip
< X-Checksum-Sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
< Content-Type: application/vnd.org.jfrog.artifactory.storage.ItemCreated+json;charset=ISO-8859-1
< Transfer-Encoding: chunked
< Date: Wed, 15 Sep 2021 21:22:56 GMT
<
christianb#christianb-mac hashicorp %
And the resty call looks like this:
PUT /artifactory/example-local-repo/crash.zip HTTP/1.1
Host: 127.0.0.1
User-Agent: jfrog/terraform-provider-artifactory:2.3.1
Content-Length: 4007
Accept: */*
Authorization: Basic cccxxx=
Content-Type: multipart/form-data; boundary=a8cddfc21bc1ecdf09e0c82e2e0ea2ac7627c4cbfeae3e51ed9e68987a99
Accept-Encoding: gzip
--a8cddfc21bc1ecdf09e0c82e2e0ea2ac7627c4cbfeae3e51ed9e68987a99
Content-Disposition: form-data; name="crash.zip"; filename="../../samples/crash.zip"
Content-Type: application/zip
...
HTTP/1.1 405
X-JFrog-Version: Artifactory/7.24.3 72403900
X-Artifactory-Id: 65b0c15e32af425b:-53411fa9:17be4f9b6e8:-8000
X-Artifactory-Node-Id: cb4b887aed9e
Allow: OPTIONS, GET, HEAD, POST
Content-Type: application/json;charset=ISO-8859-1
Content-Length: 65
Date: Wed, 15 Sep 2021 21:41:07 GMT
{
"errors" : [ {
"status" : 405,
"message" : ""
} ]
}
So, clearly resty is treating this as a multi-part upload, which is wrong.
Does anyone know the equivalent resty call to this curl command?
I've tried:
uri := "/artifactory/" + remotePath
reader, err := os.Open(localPath)
if err != nil {
return err
}
_, err = client.R().SetBody(reader).
SetHeader("Content-Type", contentType).Put(uri)
and
_, err = client.R().SetFileReader(filepath.Base(localPath), localPath, reader).
SetHeader("Content-Type", contentType).Put(uri)
and
uri := "/artifactory/" + remotePath
_, err := client.R().SetFile(filepath.Base(localPath),localPath).
SetHeader("Content-Type", contentType).Put(uri)
None work.

SetFileReader and SetFile are both intended to be used for multipart uploads.
SetBody is the right function to use, but I believe you need to read in the file contents first and then pass the bytes to SetBody:
uri := "/artifactory/" + remotePath
data, err := os.ReadFile(localPath)
if err != nil {
return err
}
_, err = client.R().SetBody(data).
SetHeader("Content-Type", contentType).Put(uri)

Related

can't use curl to query neo4j

I am trying to use curl to query neo4j
curl -X POST -H Accept:application/json -H Content-Type:application/json -u neo4j:password -v http://localhost:7474/db/neo4j/tx/commit -d '{"statements":[{"statement":"MATCH (n) RETURN n"}]}'
gives me this response
Note: Unnecessary use of -X or --request, POST is already inferred.
* Trying 127.0.0.1:7474...
* Connected to localhost (127.0.0.1) port 7474 (#0)
* Server auth using Basic with user 'neo4j'
> POST /db/neo4j/tx/commit HTTP/1.1
> Host: localhost:7474
> Authorization: Basic bmVvNGo6cGFzc3dvcmQ=
> User-Agent: curl/7.79.1
> Accept:application/json
> Content-Type:application/json
> Content-Length: 47
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Date: Wed, 27 Jul 2022 09:13:35 GMT
< Access-Control-Allow-Origin: *
< Content-Type: application/json
< Content-Length: 120
<
{"results":[],"errors":[{"code":"Neo.ClientError.Request.InvalidFormat","message":"Could not parse the incoming JSON"}]}* Connection #0 to host localhost left intact
If anyone could help please
Should have mentioned I'm on windows. Apparently you have to escape those double quotes in the json
This works for me now:
curl -X POST -H Accept:application/json -H Content-Type:application/json -u neo4j:password -v http://localhost:7474/db/neo4j/tx/commit -d "{\"statements\":[{\"statement\":\"MATCH (n) RETURN n\"}]}"

Using PDF Reactor as Web Service

I am discovering PDF reactor and I'd like to use it as a web service. To test a file, I use cURL
curl -v -X POST --header "Content-Type:application/xml" http://localhost:9423/service/rest/convert/async -d #test.html
Is that correct ?
test.html :
<html>
<body>
Coucou, je suis terrien.
</body>
</html>
Thank you for your help,
Cédrik
edit #1:
response from the comman above :
* About to connect() to localhost port 9423 (#0)
* Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 9423 (#0)
> POST /service/rest/convert/async HTTP/1.1
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.3.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Host: localhost:9423
> Accept: */*
> Content-Type:application/xml
> Content-Length: 50
>
< HTTP/1.1 400 Bad Request
< Content-Type: text/plain
< Date: Tue, 15 Dec 2015 11:47:29 GMT
< Content-Length: 307
< Server: Jetty(9.3.2.v20150730)
<
* Connection #0 to host localhost left intact
* Closing connection #0
JAXBException occurred : élément inattendu (URI : "", local : "html"). Les éléments attendus sont <{http://webservice.pdfreactor.realobjects.com/}configuration>. élément inattendu (URI : "", local : "html"). Les éléments attendus sont <{http://webservice.pdfreactor.realobjects.com/}configuration>.
When using the REST API of PDFreactor via cURL you have to send a configuration XML or JSON to the server which includes configuration for PDFreactor and your document, as described here: http://www.pdfreactor.com/product/doc_html/index.html#d0e688
A sample configuration for XML could look like this:
config.xml:
<tns:configuration xmlns:tns="http://webservice.pdfreactor.realobjects.com/">
<document><html> <body> Coucou, je suis terrien. </body> </html></document>
</tns:configuration>
You can then call the following:
curl -v -X POST --header "Content-Type:application/xml" http://localhost:9423/service/rest/convert/async.xml -d #config.xml
The output will look like the following:
* About to connect() to localhost port 9423
* Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 9423
> POST /service/rest/convert/async.xml HTTP/1.1
> User-Agent: curl/7.15.5 (x86_64-redhat-linux-gnu) libcurl/7.15.5 OpenSSL/0.9.8b zlib/1.2.3 libidn/0.6.5
> Host: localhost:9423
> Accept: */*
> Content-Type:application/xml
> Content-Length: 195
>
> <tns:configuration xmlns:tns="http://webservice.pdfreactor.realobjects.com/"> <document><html><body>Coucou, je suis terrien.</body></html></document></tns:configuration>HTTP/1.1 202 Accepted
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Headers: Accept, Content-Length, content-type, Host, User-Agent
< Access-Control-Allow-Methods: GET, PUT, POST, DELETE
< Access-Control-Expose-Headers: Location
< Cache-Control: no-cache
< Date: Wed, 16 Dec 2015 16:34:19 GMT
< Location: http://localhost:9423/service/rest/progress/c2a58dbd-ef9d-4b79-87d9-079c139fe9ed
< Content-Length: 0
< Server: Jetty(9.3.2.v20150730)
* Connection #0 to host localhost left intact
* Closing connection #0
The "Location" response header contains the URL which can be used to retrieve the progress of the conversion, so you can retrieve the progress with (the ID will of course vary):
curl -v http://localhost:9423/service/rest/progress/c2a58dbd-ef9d-4b79-87d9-079c139fe9ed
This will return the conversion progress and if the conversion has finished the "Location" repsonse header will contain a new URL to retrieve the document. You can use ".pdf" to retrieve the PDF binary data or ".xml" to retrieve XML data containing the PDF as base64 encoded String, the number of pages of the document, etc.
curl -v http://localhost:9423/service/rest/document/c2a58dbd-ef9d-4b79-87d9-079c139fe9ed.pdf

Django-rest-framework token auth doesn't work

I'm trying to POST json data to url, decorated with login_required, but django returns redirect to login page
DRF setup:
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
and rest_framework.authtoken in INSTALLED_APPS
I can obtain auth token via curl
$ curl -X POST -d "{\"username\" : 7, \"password\" : 1}" -H "Content-Type: application/json" http://127.0.0.1:9000/extapi/get-auth-token/
{"token":"bc61497d98bed02bd3a84af2235365d0b2b549ff"}
But when i POST to the view, decorated with login_required, django returns http 302 with Location header pointing to the login page.
$ curl -v -X POST -d '{"event":"14","user":"7","action":"1868","unit":"","value":"-1"}' -H "Content-Type: application/json" -H "Authorization: Token bc61497d98bed02bd3a84af2235365d0b2b549ff" http://127.0.0.1:9000/zk2015/events/actions/api/uservotejournal/7/
* Hostname was NOT found in DNS cache
* Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 9000 (#0)
> POST /zk2015/events/actions/api/uservotejournal/7/ HTTP/1.1
> User-Agent: curl/7.35.0
> Host: 127.0.0.1:9000
> Accept: */*
> Content-Type: application/json
> Authorization: Token bc61497d98bed02bd3a84af2235365d0b2b549ff
> Content-Length: 64
>
* upload completely sent off: 64 out of 64 bytes
< HTTP/1.1 302 FOUND
* Server nginx/1.4.6 (Ubuntu) is not blacklisted
< Server: nginx/1.4.6 (Ubuntu)
< Date: Fri, 18 Sep 2015 11:14:31 GMT
< Content-Type: text/html; charset=utf-8
< Location: http://127.0.0.1:9000/accounts/login/?next=/zk2015/events/actions/api/uservotejournal/7/
< Transfer-Encoding: chunked
< Connection: keep-alive
< Vary: Cookie
< X-Frame-Options: SAMEORIGIN
< ETag: "d41d8cd98f00b204e9800998ecf8427e"
< Set-Cookie: csrftoken=G85fWrKKsIA5a2uGPIn9fS4pqKrS51jK; expires=Fri, 16-Sep-2016 11:14:31 GMT; Max-Age=31449600; Path=/
<
* Connection #0 to host 127.0.0.1 left intact
I've tried to set breakpoints in rest_framework.authentication.SessionAuthentication and rest_framework.authentication.TokenAuthentication, but they were never fired
What is wrong in my setup? Help, please.
You are not passing the Authorization in Header in the curl
curl -X POST -d "{\"username\" : 7, \"password\" : 1}" -H "Authorization: Token bc61497d98bed02bd3a84af2235365d0b2b549ff" http://127.0.0.1:9000/extapi/get-auth-token/
The point is that request.user is AnonymousUser in drf.APIView.dispatch(), but is defined as authorized user in drf.APIView.post() and other similar methods.
This differs from django: request.user is defined as authorized user in django.views.View.dispatch()
Also that is the cause, why django.contrib.auth.decorators.login_required is not compatible whith drf views.

Anyway to compress HTML output with Martini?

In a quasi-embedded environment so speed is everything. I have found that if I compress my .html files, the app is speedier. Is there a flag or way in Martini to do this on the fly?
You can use gzip Middleware
https://github.com/codegangsta/martini-contrib/tree/master/gzip
import (
"github.com/codegangsta/martini"
"github.com/codegangsta/martini-contrib/gzip"
)
func main() {
m := martini.Classic()
// gzip every request
m.Use(gzip.All())
m.Run()
}
This answer is just to show that #fabrizioM's answer actually works:
Step 1: Create the server
package main
import (
"github.com/codegangsta/martini"
"github.com/codegangsta/martini-contrib/gzip"
)
func main() {
m := martini.Classic()
// gzip every request
m.Use(gzip.All())
m.Get("/hello", func() string {
return "Hello, World!"
})
m.Run()
}
Step 2: Run the server
go run main.go
Step 3: Try the server
This is the step where you must remember to include the Accept-Encoding: gzip header (or equivalent).
Without compression:
curl --dump-header http://localhost:3000/hello
HTTP/1.1 200 OK
Date: Wed, 09 Jul 2014 17:19:35 GMT
Content-Length: 13
Content-Type: text/plain; charset=utf-8
Hello, World!
With compression:
curl --dump-header http://localhost:3000/hello -H 'Accept-Encoding: gzip'
HTTP/1.1 200 OK
Content-Encoding: gzip
Content-Type: text/plain; charset=utf-8
Vary: Accept-Encoding
Date: Wed, 09 Jul 2014 17:21:02 GMT
Content-Length: 37
� n��Q��J

GZIP encoding in Jersey 2 / Grizzly

I can't activate gzip-encoding in my Jersey service. This is what I've tried:
Started out with the jersey-quickstart-grizzly2 archetype from the Getting Started Guide.
Added rc.register(org.glassfish.grizzly.http.GZipContentEncoding.class);
(have also tried rc.register(org.glassfish.jersey.message.GZipEncoder.class);)
Started with mvn exec:java
Tested with curl --compressed -v -o - http://localhost:8080/myapp/myresource
The result is the following:
> GET /myapp/myresource HTTP/1.1
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 zlib/1.2.3.4 ...
> Host: localhost:8080
> Accept: */*
> Accept-Encoding: deflate, gzip
>
< HTTP/1.1 200 OK
< Content-Type: text/plain
< Date: Sun, 03 Nov 2013 08:07:10 GMT
< Content-Length: 7
<
* Connection #0 to host localhost left intact
* Closing connection #0
Got it!
That is, despite Accept-Encoding: deflate, gzip in the request, there is no Content-Encoding: gzip in the response.
What am I missing here??
You have to register the org.glassfish.jersey.server.filter.EncodingFilter as well. This example enables deflate and gzip compression:
import org.glassfish.jersey.message.DeflateEncoder;
import org.glassfish.jersey.message.GZipEncoder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.filter.EncodingFilter;
...
private void enableCompression(ResourceConfig rc) {
rc.registerClasses(
EncodingFilter.class,
GZipEncoder.class,
DeflateEncoder.class);
}
This solution is jersey specific and works not only with Grizzly, but with the JDK Http server as well.
Try the code like:
HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(
BASE_URI, rc, false);
CompressionConfig compressionConfig =
httpServer.getListener("grizzly").getCompressionConfig();
compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.ON); // the mode
compressionConfig.setCompressionMinSize(1); // the min amount of bytes to compress
compressionConfig.setCompressableMimeTypes("text/plain", "text/html"); // the mime types to compress
httpServer.start();

Resources