aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/neh/http_headers.h
blob: e3c9867d06489fef4292196ab42264dc59fc0a12 (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);
            }
        }
    }
}