Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

5
Task/HTTPS/00-META.yaml Normal file
View file

@ -0,0 +1,5 @@
---
category:
- Networking and Web Interaction
from: http://rosettacode.org/wiki/HTTPS
note: Programming environment operations

5
Task/HTTPS/00-TASK.txt Normal file
View file

@ -0,0 +1,5 @@
;Task:
Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console.<br>
Checking the host certificate for validity is recommended.<br>
Do not authenticate. That is the subject of other [[HTTPS request with authentication|tasks]].<br>
Readers may wish to contrast with the [[HTTP Request]] task, and also the task on [[HTTPS request with authentication]].<br>

8
Task/HTTPS/Ada/https.ada Normal file
View file

@ -0,0 +1,8 @@
with AWS.Client;
with AWS.Response;
with Ada.Text_IO; use Ada.Text_IO;
procedure GetHttps is
begin
Put_Line (AWS.Response.Message_Body (AWS.Client.Get (
URL => "https://sourceforge.net/")));
end GetHttps;

View file

@ -0,0 +1 @@
print read "https://www.w3.org/"

View file

@ -0,0 +1,7 @@
URL := "https://sourceforge.net/"
WININET_Init()
msgbox % html := UrlGetContents(URL)
WININET_UnInit()
return
#include urlgetcontents.ahk
#include wininet.ahk

View file

@ -0,0 +1,15 @@
OPTION TLS TRUE
website$ = "www.google.com"
OPEN website$ & ":443" FOR NETWORK AS mynet
SEND "GET / HTTP/1.1\r\nHost: " & website$ & "\r\n\r\n" TO mynet
WHILE WAIT(mynet, 1000)
RECEIVE dat$ FROM mynet
total$ = total$ & dat$
IF REGEX(dat$, "\r\n\r\n$") THEN BREAK : ' Quit receiving data when end indicator was reached
WEND
CLOSE NETWORK mynet
PRINT REPLACE$(total$, "\r\n[0-9a-fA-F]+\r\n", "\r\n", TRUE) : ' Remove chunk indicators from HTML data

View file

@ -0,0 +1,2 @@
:: Must have curl.exe
curl.exe -k -s -L https://sourceforge.net/

View file

@ -0,0 +1,13 @@
using System;
using System.Net;
class Program
{
static void Main(string[] args)
{
var client = new WebClient();
var data = client.DownloadString("https://www.google.com");
Console.WriteLine(data);
}
}

18
Task/HTTPS/C/https.c Normal file
View file

@ -0,0 +1,18 @@
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
CURL *curl;
char buffer[CURL_ERROR_SIZE];
int main(void) {
if ((curl = curl_easy_init()) != NULL) {
curl_easy_setopt(curl, CURLOPT_URL, "https://sourceforge.net/");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer);
if (curl_easy_perform(curl) != CURLE_OK) {
fprintf(stderr, "%s\n", buffer);
return EXIT_FAILURE;
}
curl_easy_cleanup(curl);
}
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,2 @@
(use '[clojure.contrib.duck-streams :only (slurp*)])
(print (slurp* "https://sourceforge.net"))

View file

@ -0,0 +1 @@
(print (slurp "https://sourceforge.net"))

View file

@ -0,0 +1,13 @@
(defun wget-drakma-string (url &optional (out *standard-output*))
"Grab the body as a string, and write it to out."
(write-string (drakma:http-request url) out))
(defun wget-drakma-stream (url &optional (out *standard-output*))
"Grab the body as a stream, and write it to out."
(loop with body = (drakma:http-request url :want-stream t)
for line = (read-line body nil nil)
while line do (write-line line)
finally (close body)))
;; Use
(wget-drakma-stream "https://sourceforge.net")

View file

@ -0,0 +1 @@
(format t "~a~%" (nth-value 0 (dex:get "https://www.w3.org/")))

2
Task/HTTPS/D/https.d Normal file
View file

@ -0,0 +1,2 @@
auto data = get("https://sourceforge.net");
writeln(data);

View file

@ -0,0 +1,20 @@
program ShowHTTPS;
{$APPTYPE CONSOLE}
uses IdHttp, IdSSLOpenSSL;
var
s: string;
lHTTP: TIdHTTP;
begin
lHTTP := TIdHTTP.Create(nil);
try
lHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP);
lHTTP.HandleRedirects := True;
s := lHTTP.Get('https://sourceforge.net/');
Writeln(s);
finally
lHTTP.Free;
end;
end.

View file

@ -0,0 +1,4 @@
;; asynchronous call back definition
(define (success name text) (writeln 'Loaded name) (writeln text))
;;
(file->string success "https:/sourceforge.net")

View file

@ -0,0 +1,10 @@
-module(main).
-export([main/1]).
main([Url|[]]) ->
inets:start(),
ssl:start(),
case http:request(get, {URL, []}, [{ssl,[{verify,0}]}], []) of
{ok, {_V, _H, Body}} -> io:fwrite("~p~n",[Body]);
{error, Res} -> io:fwrite("~p~n", [Res])
end.

View file

@ -0,0 +1,12 @@
-module(main).
-export([main/1]).
main([Url|[]]) ->
inets:start(),
ssl:start(),
http:request(get, {Url, [] }, [{ssl,[{verify,0}]}], [{sync, false}]),
receive
{http, {_ReqId, Res}} -> io:fwrite("~p~n",[Res]);
_Any -> io:fwrite("Error: ~p~n",[_Any])
after 10000 -> io:fwrite("Timed out.~n",[])
end.

View file

@ -0,0 +1 @@
|escript ./req.erl https://sourceforge.net/

View file

@ -0,0 +1,4 @@
#light
let wget (url : string) =
let c = new System.Net.WebClient()
c.DownloadString(url)

View file

@ -0,0 +1 @@
print[read["https://sourceforge.net/"]]

16
Task/HTTPS/Go/https.go Normal file
View file

@ -0,0 +1,16 @@
package main
import (
"io"
"log"
"net/http"
"os"
)
func main() {
r, err := http.Get("https://sourceforge.net/")
if err != nil {
log.Fatalln(err)
}
io.Copy(os.Stdout, r.Body)
}

View file

@ -0,0 +1 @@
new URL("https://sourceforge.net").eachLine { println it }

View file

@ -0,0 +1,8 @@
#!/usr/bin/runhaskell
import Network.HTTP.Conduit
import qualified Data.ByteString.Lazy as L
import Network (withSocketsDo)
main = withSocketsDo
$ simpleHttp "https://sourceforge.net/" >>= L.putStr

View file

@ -0,0 +1,7 @@
# Requires Unicon version 13
procedure main(arglist)
url := (\arglist[1] | "https://sourceforge.net/")
w := open(url, "m-") | stop("Cannot open " || url)
while write(read(w))
close(w)
end

View file

@ -0,0 +1,6 @@
connection = URL new("https://sourceforge.net") openConnection
scanner = Scanner new(connection getInputStream)
while(scanner hasNext,
scanner next println
)

4
Task/HTTPS/J/https.j Normal file
View file

@ -0,0 +1,4 @@
#page=: gethttp'https://sourceforge.net'
0
#page=: '--no-check-certificate' gethttp'https://sourceforge.net'
900

View file

@ -0,0 +1,7 @@
URL url = new URL("https://sourceforge.net");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
Scanner scanner = new Scanner(connection.getInputStream());
while (scanner.hasNext()) {
System.out.println(scanner.next());
}

View file

@ -0,0 +1,19 @@
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.Charset;
public class Main {
public static void main(String[] args) {
var request = HttpRequest.newBuilder(URI.create("https://sourceforge.net"))
.GET()
.build();
HttpClient.newHttpClient()
.sendAsync(request, HttpResponse.BodyHandlers.ofString(Charset.defaultCharset()))
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
}
}

View file

@ -0,0 +1,5 @@
fetch("https://sourceforge.net").then(function (response) {
return response.text();
}).then(function (body) {
return body;
});

View file

@ -0,0 +1,11 @@
require("https").get("https://sourceforge.net", function (resp) {
let body = "";
resp.on("data", function (chunk) {
body += chunk;
});
resp.on("end", function () {
console.log(body);
});
}).on("error", function (err) {
console.error("Error: " + err.message);
});

View file

@ -0,0 +1,5 @@
# v0.6.0
using Requests
str = readstring(get("https://sourceforge.net/"))

View file

@ -0,0 +1,14 @@
// version 1.1.2
import java.net.URL
import javax.net.ssl.HttpsURLConnection
import java.io.InputStreamReader
import java.util.Scanner
fun main(args: Array<String>) {
val url = URL("https://en.wikipedia.org/wiki/Main_Page")
val connection = url.openConnection() as HttpsURLConnection
val isr = InputStreamReader(connection.inputStream)
val sc = Scanner(isr)
while (sc.hasNextLine()) println(sc.nextLine())
sc.close()
}

View file

@ -0,0 +1,5 @@
import java.net.URL
fun main(args: Array<String>){
println(URL("https://sourceforge.net").readText())
}

20
Task/HTTPS/LSL/https.lsl Normal file
View file

@ -0,0 +1,20 @@
string sURL = "https://SourceForge.Net/";
key kHttpRequestId;
default {
state_entry() {
kHttpRequestId = llHTTPRequest(sURL, [], "");
}
http_response(key kRequestId, integer iStatus, list lMetaData, string sBody) {
if(kRequestId==kHttpRequestId) {
llOwnerSay("Status="+(string)iStatus);
integer x = 0;
for(x=0 ; x<llGetListLength(lMetaData) ; x++) {
llOwnerSay("llList2String(lMetaData, "+(string)x+")="+llList2String(lMetaData, x));
}
list lBody = llParseString2List(sBody, ["\n"], []);
for(x=0 ; x<llGetListLength(lBody) ; x++) {
llOwnerSay("llList2String(lBody, "+(string)x+")="+llList2String(lBody, x));
}
}
}
}

View file

@ -0,0 +1,3 @@
local(x = curl('https://sourceforge.net'))
local(y = #x->result)
#y->asString

View file

@ -0,0 +1,10 @@
ch = xtra("Curl").new()
CURLOPT_URL = 10002
ch.setOption(CURLOPT_URL, "https://sourceforge.net")
res = ch.exec(1)
if integerP(res) then
put "Error:" && curl_error(res)
else
put "Result:" && res.readRawString(res.length)
end if
-- "Result: <!doctype html> ..."

View file

@ -0,0 +1,2 @@
sx = xtra("Shell").new()
put sx.shell_cmd("curl https://sourceforge.net")

View file

@ -0,0 +1,2 @@
libURLSetSSLVerification true --check cert
get URL "https://sourceforge.net/"

View file

@ -0,0 +1,10 @@
on myUrlDownloadFinished
get URL "https://sourceforge.net/" -- this will now fetch a locally cached copy
put it
end myUrlDownloadFinished
command getWebResource
libURLFollowHttpRedirects true
libURLSetSSLVerification true --check cert
load URL "https://sourceforge.net/" with message "myUrlDownloadFinished"
end getWebResource

5
Task/HTTPS/Lua/https.lua Normal file
View file

@ -0,0 +1,5 @@
local request = require('http.request')
local headers, stream = request.new_from_uri("https://sourceforge.net/"):go()
local body = stream:get_body_as_string()
local status = headers:get(':status')
io.write(string.format('Status: %d\nBody: %s\n', status, body)

View file

@ -0,0 +1 @@
s=urlread('https://sourceforge.net/')

View file

@ -0,0 +1 @@
content := URL:-Get( "https://www.google.ca/" );

View file

@ -0,0 +1 @@
content=Import["https://sourceforge.net", "HTML"]

View file

@ -0,0 +1,17 @@
using System;
using System.Console;
using System.Net;
using System.IO;
module HTTP
{
Main() : void
{
def wc = WebClient();
def myStream = wc.OpenRead(https://sourceforge.com);
def sr = StreamReader(myStream);
WriteLine(sr.ReadToEnd());
myStream.Close()
}
}

View file

@ -0,0 +1 @@
(! "curl https://sourceforge.net")

4
Task/HTTPS/Nim/https.nim Normal file
View file

@ -0,0 +1,4 @@
import httpclient
var client = newHttpClient()
echo client.getContent("https://sourceforge.net")

View file

@ -0,0 +1,11 @@
use HTTP;
class HttpsTest {
function : Main(args : String[]) ~ Nil {
client := HttpsClient->New();
lines := client->Get("https://sourceforge.net");
each(i : lines) {
lines->Get(i)->As(String)->PrintLine();
};
}
}

5
Task/HTTPS/Ol/https.ol Normal file
View file

@ -0,0 +1,5 @@
(import (lib curl))
(define curl (make-curl))
(curl 'url "https://www.w3.org/")
(curl 'perform)

1
Task/HTTPS/PHP/https.php Normal file
View file

@ -0,0 +1 @@
echo file_get_contents('https://sourceforge.net');

View file

@ -0,0 +1,16 @@
{$mode objfpc}{$H+}
uses fphttpclient;
var
s: string;
hc: tfphttpclient;
begin
hc := tfphttpclient.create(nil);
try
s := hc.get('https://www.example.com')
finally
hc.free
end;
writeln(s)
end.

9
Task/HTTPS/Perl/https.pl Normal file
View file

@ -0,0 +1,9 @@
use strict;
use LWP::UserAgent;
my $url = 'https://www.rosettacode.org';
my $response = LWP::UserAgent->new->get( $url );
$response->is_success or die "Failed to GET '$url': ", $response->status_line;
print $response->as_string;

View file

@ -0,0 +1,12 @@
(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">libcurl</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #7060A8;">curl_global_init</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">curl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">curl_easy_init</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">curl_easy_setopt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLOPT_URL</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"https://sourceforge.net/"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">curl_easy_perform_ex</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">curl_easy_cleanup</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">curl_global_cleanup</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
<!--

View file

@ -0,0 +1,2 @@
(in '(curl "https://sourceforge.net") # Open a pipe to 'curl'
(out NIL (echo)) ) # Echo to standard output

View file

@ -0,0 +1,3 @@
int main() {
write("%s\n", Protocols.HTTP.get_url_data("https://sourceforge.net"));
}

View file

@ -0,0 +1,2 @@
$wc = New-Object Net.WebClient
$wc.DownloadString('https://sourceforge.net')

View file

@ -0,0 +1,2 @@
import urllib.request
print(urllib.request.urlopen("https://sourceforge.net/").read())

2
Task/HTTPS/R/https-1.r Normal file
View file

@ -0,0 +1,2 @@
library(RCurl)
webpage <- getURL("https://sourceforge.net/", .opts=list(followlocation=TRUE, ssl.verifyhost=FALSE, ssl.verifypeer=FALSE))

2
Task/HTTPS/R/https-2.r Normal file
View file

@ -0,0 +1,2 @@
wp <- readLines(tc <- textConnection(webpage))
close(tc)

2
Task/HTTPS/R/https-3.r Normal file
View file

@ -0,0 +1,2 @@
pagetree <- htmlTreeParse(wp)
pagetree$children$html

View file

@ -0,0 +1,2 @@
Dim sock As New HTTPSecureSocket
Print(sock.Get("https://sourceforge.net", 10)) //set the timeout period to 10 seconds.

View file

@ -0,0 +1,5 @@
#lang racket
(require net/url)
(copy-port (get-pure-port (string->url "https://www.google.com")
#:redirections 100)
(current-output-port))

View file

@ -0,0 +1,2 @@
use WWW;
say get 'https://sourceforge.net/';

View file

@ -0,0 +1,2 @@
use HTTP::UserAgent;
say HTTP::UserAgent.new.get('https://sourceforge.net/').content;

View file

@ -0,0 +1,2 @@
cStr= download("http://sourceforge.net/")
see cStr + nl

15
Task/HTTPS/Ruby/https.rb Normal file
View file

@ -0,0 +1,15 @@
require 'net/https'
require 'uri'
require 'pp'
uri = URI.parse('https://sourceforge.net')
http = Net::HTTP.new(uri.host,uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.start do
content = http.get(uri)
p [content.code, content.message]
pp content.to_hash
puts content.body
end

View file

@ -0,0 +1,10 @@
extern crate reqwest;
fn main() {
let response = match reqwest::blocking::get("https://sourceforge.net") {
Ok(response) => response,
Err(e) => panic!("error encountered while making request: {:?}", e),
};
println!("{}", response.text().unwrap());
}

View file

@ -0,0 +1,7 @@
import scala.io.Source
object HttpsTest extends App {
System.setProperty("http.agent", "*")
Source.fromURL("https://sourceforge.net").getLines.foreach(println)
}

View file

@ -0,0 +1,8 @@
$ include "seed7_05.s7i";
include "gethttps.s7i";
include "utf8.s7i";
const proc: main is func
begin
writeln(STD_UTF8_OUT, getHttps("sourceforge.net"));
end func;

View file

@ -0,0 +1,11 @@
var lwp = require('LWP::UserAgent'); # LWP::Protocol::https is needed
var url = 'https://rosettacode.org';
var ua = lwp.new(
agent => 'Mozilla/5.0',
ssl_opts => Hash.new(verify_hostname => 1),
);
var resp = ua.get(url);
resp.is_success || die "Failed to GET #{url.dump}: #{resp.status_line}";
print resp.decoded_content;

View file

@ -0,0 +1,15 @@
import Foundation
// With https
let request = NSURLRequest(URL: NSURL(string: "https://sourceforge.net")!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {res, data, err in // callback
// data is binary
if (data != nil) {
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)
println(string)
}
}
CFRunLoopRun() // dispatch

View file

@ -0,0 +1,3 @@
$$ MODE TUSCRIPT
SET DATEN = REQUEST ("https://sourceforge.net")
*{daten}

16
Task/HTTPS/Tcl/https.tcl Normal file
View file

@ -0,0 +1,16 @@
package require http
package require tls
# Tell the http package what to do with https: URLs.
#
# First argument is the protocol name, second the default port, and
# third the connection builder command
http::register "https" 443 ::tls::socket
# Make a secure connection, which is almost identical to normal
# connections except for the different protocol in the URL.
set token [http::geturl "https://sourceforge.net/"]
# Now as for conventional use of the http package
puts [http::data $token]
http::cleanup $token

View file

@ -0,0 +1 @@
curl -k -s -L https://sourceforge.net/

View file

@ -0,0 +1,17 @@
Option Explicit
Const sURL="https://sourceforge.net/"
Dim oHTTP
Set oHTTP = CreateObject("Microsoft.XmlHTTP")
On Error Resume Next
oHTTP.Open "GET", sURL, False
oHTTP.Send ""
If Err.Number = 0 Then
WScript.Echo oHTTP.responseText
Else
Wscript.Echo "error " & Err.Number & ": " & Err.Description
End If
Set oHTTP = Nothing

View file

@ -0,0 +1,5 @@
Imports System.Net
Dim client As WebClient = New WebClient()
Dim content As String = client.DownloadString("https://sourceforge.net")
Console.WriteLine(content)

View file

@ -0,0 +1,21 @@
Sub Main()
Dim HttpReq As WinHttp.WinHttpRequest
' in the "references" dialog of the IDE, check
' "Microsoft WinHTTP Services, version 5.1" (winhttp.dll)
Const HTTPREQUEST_PROXYSETTING_PROXY As Long = 2
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 As Long = &H80&
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 As Long = &H200&
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 As Long = &H800&
#Const USE_PROXY = 1
Set HttpReq = New WinHttp.WinHttpRequest
HttpReq.Open "GET", "https://groups.google.com/robots.txt"
HttpReq.Option(WinHttpRequestOption_SecureProtocols) = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 Or _
WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 Or _
WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2
#If USE_PROXY Then
HttpReq.SetProxy HTTPREQUEST_PROXYSETTING_PROXY, "my_proxy:80"
#End If
HttpReq.SetTimeouts 1000, 1000, 1000, 1000
HttpReq.Send
Debug.Print HttpReq.ResponseText
End Sub

View file

@ -0,0 +1,31 @@
/* https.wren */
var CURLOPT_URL = 10002
var CURLOPT_FOLLOWLOCATION = 52
var CURLOPT_ERRORBUFFER = 10010
foreign class Curl {
construct easyInit() {}
foreign easySetOpt(opt, param)
foreign easyPerform()
foreign easyCleanup()
}
var curl = Curl.easyInit()
if (curl == 0) {
System.print("Error initializing cURL.")
return
}
curl.easySetOpt(CURLOPT_URL, "https://www.w3.org/")
curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1)
curl.easySetOpt(CURLOPT_ERRORBUFFER, 0) // buffer to be supplied by C
var status = curl.easyPerform()
if (status != 0) {
System.print("Failed to perform task.")
return
}
curl.easyCleanup()

View file

@ -0,0 +1,127 @@
/* gcc https.c -o https -lcurl -lwren -lm */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
/* C <=> Wren interface functions */
void C_curlAllocate(WrenVM* vm) {
CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*));
*pcurl = curl_easy_init();
}
void C_easyPerform(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
CURLcode cc = curl_easy_perform(curl);
wrenSetSlotDouble(vm, 0, (double)cc);
}
void C_easyCleanup(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
curl_easy_cleanup(curl);
}
void C_easySetOpt(WrenVM* vm) {
CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0);
CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1);
if (opt < 10000) {
long lparam = (long)wrenGetSlotDouble(vm, 2);
curl_easy_setopt(curl, opt, lparam);
} else {
if (opt == CURLOPT_URL) {
const char *url = wrenGetSlotString(vm, 2);
curl_easy_setopt(curl, opt, url);
} else if (opt == CURLOPT_ERRORBUFFER) {
char buffer[CURL_ERROR_SIZE];
curl_easy_setopt(curl, opt, buffer);
}
}
}
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.allocate = NULL;
methods.finalize = NULL;
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Curl") == 0) {
methods.allocate = C_curlAllocate;
}
}
return methods;
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Curl") == 0) {
if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt;
if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform;
if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "https.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}

3
Task/HTTPS/Zkl/https.zkl Normal file
View file

@ -0,0 +1,3 @@
zkl: var ZC=Import("zklCurl")
zkl: var data=ZC().get("https://sourceforge.net")
L(Data(36,265),826,0)