jgauffin / Griffin.WebServer

A web server built on top of Griffin.Framework
107 stars 42 forks source link

HttpResponseCookies are not written back to the browser #31

Open henon opened 7 years ago

henon commented 7 years ago

I searched, there is no mention of the string "Set-Cookie" in the whole code.

henon commented 7 years ago

Here is my working solution in case somebody cares: HttpMessageEncoder's Send method:

     /// <summary>
    ///     Buffer structure used for socket send operations.
    /// </summary>
    /// <param name="buffer">
    ///     Do note that there are not buffer attached to the structure, you have to assign one yourself using
    ///     <see cref="ISocketBuffer.SetBuffer(int,int)" />. This choice was made
    ///     to prevent unnecessary copy operations.
    /// </param>
    public void Send(ISocketBuffer buffer)
    {
        // last send operation did not send all bytes enqueued in the buffer
        // so let's just continue until doing next message
        if (_bytesToSend > 0)
        {
            buffer.SetBuffer(_buffer, _offset, _bytesToSend);
            return;
        }

        // continuing with the message body
        if (_isHeaderSent)
        {
            var bytes = Math.Min(_totalAmountToSend, _buffer.Length);
            _message.Body.Read(_buffer, 0, bytes);
            _bytesToSend = bytes;

            buffer.SetBuffer(_buffer, 0, bytes);
            return;
        }

        _headerWriter.WriteLine(_message.StatusLine);
        foreach (var header in _message.Headers)
        {
            _headerWriter.Write("{0}: {1}\r\n", header.Key, header.Value);
        }
        // mr: added cookies to response
        if (_message is HttpResponse)
        {
            var response = _message as HttpResponse;
            foreach(var cookie in response.Cookies.OfType<HttpResponseCookie>())
                _headerWriter.Write("Set-Cookie: {0}\r\n", cookie.ToString());
        }
        _headerWriter.Write("\r\n");
        _headerWriter.Flush();
        _isHeaderSent = true;
        buffer.UserToken = _message;

        if (_message.Body == null || _message.ContentLength == 0)
        {
            _bytesToSend = (int) _stream.Length;
            _totalAmountToSend = _bytesToSend;
            buffer.SetBuffer(_buffer, 0, (int) _stream.Length);
            return;
        }
        else
        {

        }

        var bytesLeft = _buffer.Length - _stream.Length;
        var bytesToSend = Math.Min(_message.ContentLength, (int) bytesLeft);
        var offset = (int) _stream.Position;
        _message.Body.Read(_buffer, offset, bytesToSend);
        _bytesToSend = (int) _stream.Length + bytesToSend;
        _totalAmountToSend = (int) _stream.Length + _message.ContentLength;
        buffer.SetBuffer(_buffer, 0, _bytesToSend);
    }