2019-06-23 04:21:30 +02:00
|
|
|
// Copyright (c) 2019 Alexander Medvednikov. All rights reserved.
|
|
|
|
// Use of this source code is governed by an MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
|
|
|
|
2019-06-22 20:20:28 +02:00
|
|
|
module http
|
|
|
|
|
|
|
|
struct Request {
|
|
|
|
pub:
|
|
|
|
// headers []string
|
|
|
|
headers map_string
|
|
|
|
method string
|
|
|
|
// cookies map[string]string
|
|
|
|
h string
|
|
|
|
cmd string
|
|
|
|
typ string // GET POST
|
|
|
|
data string
|
|
|
|
url string
|
|
|
|
ws_func voidptr
|
|
|
|
user_ptr voidptr
|
|
|
|
verbose bool
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Response {
|
|
|
|
pub:
|
|
|
|
body string
|
|
|
|
headers map_string
|
|
|
|
status_code int
|
|
|
|
}
|
|
|
|
|
|
|
|
// embed 'http'
|
2019-07-29 19:18:26 +02:00
|
|
|
pub fn fetch(typ, url, data string) ?Response {
|
|
|
|
req := new_request('GET', url, '') or {
|
|
|
|
return error(err)
|
2019-06-22 20:20:28 +02:00
|
|
|
}
|
|
|
|
resp := req.do()
|
2019-07-29 19:18:26 +02:00
|
|
|
return resp
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get(url string) ?string {
|
|
|
|
resp := fetch('GET', url, '') or {
|
|
|
|
return error(err)
|
|
|
|
}
|
2019-06-22 20:20:28 +02:00
|
|
|
return resp.body
|
|
|
|
}
|
|
|
|
|
2019-07-29 19:18:26 +02:00
|
|
|
pub fn post(url, data string) ?string {
|
|
|
|
resp := fetch('POST', url, data) or {
|
|
|
|
return error(err)
|
|
|
|
}
|
2019-06-22 20:20:28 +02:00
|
|
|
return resp.body
|
|
|
|
}
|
|
|
|
|
2019-07-29 19:18:26 +02:00
|
|
|
pub fn new_request(typ, _url, _data string) ?Request {
|
|
|
|
if _url == '' {
|
|
|
|
return error('http: empty url')
|
|
|
|
}
|
2019-06-22 20:20:28 +02:00
|
|
|
mut url := _url
|
|
|
|
mut data := _data
|
|
|
|
// req.headers['User-Agent'] = 'V $VERSION'
|
|
|
|
if typ == 'GET' && !url.contains('?') && data != '' {
|
|
|
|
println('zeroing data, to url')
|
|
|
|
url = '$url?$data'
|
|
|
|
data = ''
|
|
|
|
}
|
|
|
|
// req.headers = new_map(0, sizeof(string))// []string{}
|
2019-07-29 19:18:26 +02:00
|
|
|
return Request {
|
2019-06-22 20:20:28 +02:00
|
|
|
typ: typ
|
2019-07-13 14:10:15 +02:00
|
|
|
url: url
|
|
|
|
data: data
|
2019-06-22 20:20:28 +02:00
|
|
|
ws_func: 0
|
|
|
|
user_ptr: 0
|
2019-07-01 02:58:49 +02:00
|
|
|
headers: map[string]string{}
|
2019-06-22 20:20:28 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn (req mut Request) free() {
|
|
|
|
req.headers.free()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn (resp mut Response) free() {
|
|
|
|
resp.headers.free()
|
|
|
|
}
|
|
|
|
|
2019-06-26 17:45:48 +02:00
|
|
|
pub fn (req mut Request) add_header(key, val string) {
|
2019-06-22 20:20:28 +02:00
|
|
|
// println('start add header')
|
|
|
|
// println('add header "$key" "$val"')
|
|
|
|
// println(key)
|
|
|
|
// println(val)
|
|
|
|
// h := '$key: $val'
|
|
|
|
// println('SET H')
|
|
|
|
// req.headers << h
|
|
|
|
req.headers[key] = val
|
|
|
|
// mut h := req.h
|
|
|
|
// h += ' -H "${key}: ${val}" '
|
|
|
|
// req.h = h
|
|
|
|
}
|
|
|
|
|