aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/neh/http_headers.h
blob: 70cf3a9fbe7d35bd3c0d5475d48b9c7f2d0ba857 (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
#pragma once

#include <util/generic/strbuf.h>
#include <util/stream/output.h>
#include <util/string/ascii.h>

namespace NNeh {
    namespace NHttp {
        template <typename Port>
        void WriteHostHeader(IOutputStream& out, TStringBuf host, Port port) {
            out << TStringBuf("Host: ") << host;
            if (port) {
                out << TStringBuf(":") << port;
            }
            out << TStringBuf("\r\n");
        }

        class THeaderSplitter {
        public:
            THeaderSplitter(TStringBuf headers)
                : Headers_(headers)
            {
            }

            bool Next(TStringBuf& header) {
                while (Headers_.ReadLine(header)) {
                    if (!header.Empty()) {
                        return true;
                    }
                }
                return false;
            }
        private:
            TStringBuf Headers_;
        };

        inline bool HasHostHeader(TStringBuf headers) {
            THeaderSplitter splitter(headers);
            TStringBuf header;
            while (splitter.Next(header)) {
                if (AsciiHasPrefixIgnoreCase(header, "Host:")) {
                    return true;
                }
            }
            return false;
        }

        template <typename Port>
        void WriteHostHeaderIfNot(IOutputStream& out, TStringBuf host, Port port, TStringBuf headers) {
            if (!NNeh::NHttp::HasHostHeader(headers)) {
                NNeh::NHttp::WriteHostHeader(out, host, port);
            }
        }
    }
}