62 lines
1.5 KiB
Odin
62 lines
1.5 KiB
Odin
package main
|
|
|
|
import curl "./libs/odin-curl/"
|
|
import "base:runtime"
|
|
import "core:encoding/json"
|
|
import "core:fmt"
|
|
import "core:mem"
|
|
import vmem "core:mem/virtual"
|
|
import "core:os"
|
|
import "core:unicode/utf8"
|
|
|
|
print_usage :: proc() {
|
|
fmt.printf("Usage:\n\t%s [city] [code] [api_key] \n", os.args[0])
|
|
os.exit(1)
|
|
}
|
|
|
|
DataContext :: struct {
|
|
data: []byte,
|
|
ctx: runtime.Context,
|
|
}
|
|
|
|
curl_web :: proc(url: string) -> []u8 {
|
|
using curl
|
|
h := easy_init()
|
|
defer easy_cleanup(h)
|
|
|
|
headers: ^curl_slist
|
|
headers = slist_append(nil, "content-type: application/json")
|
|
headers = slist_append(headers, "Accept: application/json")
|
|
headers = slist_append(headers, "charset: utf-8")
|
|
defer slist_free_all(headers)
|
|
|
|
easy_setopt(h, CURLoption.URL, url)
|
|
hres := easy_setopt(h, CURLoption.HTTPHEADER, headers)
|
|
// Verify option was set correctly:
|
|
if hres != CURLcode.OK {
|
|
fmt.println("Failed to set HTTPHEADER: ", easy_strerror(hres))
|
|
}
|
|
|
|
easy_setopt(h, CURLoption.WRITEFUNCTION, write_callback)
|
|
data := DataContext{nil, context}
|
|
easy_setopt(h, .WRITEDATA, &data)
|
|
|
|
result := easy_perform(h)
|
|
if result != CURLcode.OK {
|
|
fmt.println("Error occurred: ", result)
|
|
}
|
|
|
|
return data.data
|
|
}
|
|
|
|
|
|
write_callback :: proc "c" (contents: rawptr, size: uint, nmemb: uint, userp: rawptr) -> uint {
|
|
dc := transmute(^DataContext)userp
|
|
context = dc.ctx
|
|
total_size := size * nmemb
|
|
content_str := transmute([^]u8)contents
|
|
dc.data = make([]byte, int(total_size)) // <-- ALLOCATION
|
|
mem.copy(&dc.data[0], content_str, int(total_size))
|
|
return total_size
|
|
}
|