about summary refs log tree commit diff stats
path: root/src/io/request.nim
blob: 5e62dbc4b760cf9746f82c4d791b7a68be339026 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import options
import streams
import tables

import utils/twtstr
import types/url

type HttpMethod* = enum
  HTTP_CONNECT, HTTP_DELETE, HTTP_GET, HTTP_HEAD, HTTP_OPTIONS, HTTP_PATCH,
  HTTP_POST, HTTP_PUT, HTTP_TRACE

type
  Request* = ref RequestObj
  RequestObj* = object
    httpmethod*: HttpMethod
    url*: Url
    headers*: HeaderList
    body*: Option[string]
    multipart*: Option[MimeData]

  FileLoader* = ref object
    defaultHeaders*: HeaderList
    process*: int
    istream*: Stream
    ostream*: Stream

  LoadResult* = object
    s*: Stream
    res*: int
    contenttype*: string
    status*: int
    headers*: HeaderList
    redirect*: Option[Url]

  HeaderList* = object
    table*: Table[string, seq[string]]

# Originally from the stdlib
  MimePart* = object
    name*, content*: string
    case isFile*: bool
    of true:
      filename*, contentType*: string
      fileSize*: int64
      isStream*: bool
    else: discard

  MimeData* = object
    content*: seq[MimePart]

iterator pairs*(headers: HeaderList): (string, string) =
  for k, vs in headers.table:
    for v in vs:
      yield (k, v)

func newHeaderList*(): HeaderList =
  discard

func newHeaderList*(table: Table[string, string]): HeaderList =
  for k, v in table:
    let k = k.toHeaderCase()
    if k in result.table:
      result.table[k].add(v)
    else:
      result.table[k] = @[v]

func newRequest*(url: Url,
                 httpmethod = HTTP_GET,
                 headers: openarray[(string, string)] = [],
                 body = none(string),
                 multipart = none(MimeData)): Request =
  new(result)
  result.httpmethod = httpmethod
  result.url = url
  for it in headers:
    if it[1] != "": #TODO not sure if this is a good idea, options would probably work better
      result.headers.table[it[0]] = @[it[1]]
  result.body = body
  result.multipart = multipart

proc `[]=`*(multipart: var MimeData, k, v: string) =
  multipart.content.add(MimePart(name: k, content: v))

proc add*(headers: var HeaderList, k, v: string) =
  let k = k.toHeaderCase()
  if k notin headers.table:
    headers.table[k] = @[v]
  else:
    headers.table[k].add(v)

proc `[]=`*(headers: var HeaderList, k, v: string) =
  headers.table[k.toHeaderCase()] = @[v]

func getOrDefault*(headers: HeaderList, k: string, default = ""): string =
  let k = k.toHeaderCase()
  if k in headers.table:
    headers.table[k][0]
  else:
    default