Git Product home page Git Product logo

Comments (3)

geoperez avatar geoperez commented on August 17, 2024

There is not way right now, but I'm thinking we may include in the constructor a dictionary with the custom headers to response.

from embedio.

geoperez avatar geoperez commented on August 17, 2024

Issue resolved in new Nuget (version 1.0.20). Let me know if you get any issue.

You cant use the DefaultHeaders property from the StaticFilesModule like this:

WebServer.Module<StaticFilesModule>().DefaultHeaders.Add(Constants.HeaderPragma, HeaderPragmaValue);

Or include your headers like a Dictionary<string, string> in the StaticFilesModule constructor.

from embedio.

waynebloss avatar waynebloss commented on August 17, 2024

Thank you once again @geoperez. This is also working very well.

I am now using the following class to wrap your implementation in my application:

class StaticWebServer : IDisposable
{
    // TODO: Find a random port between a certain range.
    const string DefaultUrl = "http://127.0.0.1:9696/";

    public StaticWebServer()
    {
        _server = CreateServer();
    }

    WebServer _server;

    WebServer CreateServer()
    {
        var logger = new DebugLogger();
        var server = new WebServer(DefaultUrl, logger);

        var cwd = System.IO.Directory.GetCurrentDirectory();
        var browsePath = System.IO.Path.Combine(cwd, "browse");
        Debug.Print("Serving static files from: {0}", browsePath);

        var headers = new Dictionary<string, string>()
        {
            { Constants.HeaderCacheControl, "no-cache, no-store, must-revalidate" },
            { Constants.HeaderPragma, "no-cache" },
            { Constants.HeaderExpires, "0" }
        };

        var staticFileMod = new StaticFilesModule(browsePath, headers);
        staticFileMod.DefaultExtension = ".html";
        server.RegisterModule(staticFileMod);

        return server;
    }

    public void RunAsync()
    {
        _server.RunAsync();
    }

    public void Dispose()
    {
        Dispose(true);
    }

    void Dispose(bool disposing)
    {
        if (!disposing)
            return;

        var server = _server;
        _server = null;

        if (server == null)
            return;
        server.Dispose();
    }

    #region DebugLogger

    /// <summary>
    /// Provides a simple logger for Debug output.
    /// </summary>
    class DebugLogger : ILog
    {
        /// <summary>
        /// Writes the given line. This method is used by all other methods and it is asynchronous.
        /// </summary>
        /// <param name="color">The color.</param>
        /// <param name="format">The format.</param>
        /// <param name="args">The arguments.</param>
        private static void WriteLine(ConsoleColor color, string format, params object[] args)
        {
            var d = DateTime.Now;
            var dateTimeString = string.Format("{0}-{1}-{2} {3}:{4}:{5}.{6}",
                d.Year.ToString("0000"), d.Month.ToString("00"), d.Day.ToString("00"), d.Hour.ToString("00"),
                d.Minute.ToString("00"), d.Second.ToString("00"), d.Millisecond.ToString("000"));

            format = dateTimeString + "\t" + format;

            //ThreadPool.QueueUserWorkItem((context) =>
            //{
            //    var current = Console.ForegroundColor;
            //    Console.ForegroundColor = color;
            //    Console.WriteLine(format, args);
            //    Console.ForegroundColor = current;
            //});
            if (args != null)
                Debug.Print(format, args);
            else
                Debug.Print(format);
        }

        /// <summary>
        /// Writes an Info level message
        /// </summary>
        /// <param name="message"></param>
        public virtual void Info(object message)
        {
            InfoFormat(message.ToString(), null);
        }

        /// <summary>
        /// Writes an Error level message
        /// </summary>
        /// <param name="message"></param>
        public virtual void Error(object message)
        {
            ErrorFormat(message.ToString(), null);
        }

        /// <summary>
        /// Writes an Error message with Exception
        /// </summary>
        /// <param name="message"></param>
        /// <param name="exception"></param>
        public virtual void Error(object message, Exception exception)
        {
            ErrorFormat(message.ToString(), null);
            ErrorFormat(exception.ToString(), null);
        }

        /// <summary>
        /// Writes an Info level message with format
        /// </summary>
        /// <param name="format"></param>
        /// <param name="args"></param>
        public virtual void InfoFormat(string format, params object[] args)
        {
            WriteLine(ConsoleColor.Gray, format, args);
        }

        /// <summary>
        /// Writes a Warning level message with format
        /// </summary>
        /// <param name="format"></param>
        /// <param name="args"></param>
        public virtual void WarnFormat(string format, params object[] args)
        {
            WriteLine(ConsoleColor.DarkYellow, format, args);
        }

        /// <summary>
        /// Writes an Error level message with format
        /// </summary>
        /// <param name="format"></param>
        /// <param name="args"></param>
        public virtual void ErrorFormat(string format, params object[] args)
        {
            WriteLine(ConsoleColor.Red, format, args);
        }

        /// <summary>
        /// Writes an Debug level message with format
        /// </summary>
        /// <param name="format"></param>
        /// <param name="args"></param>
        public virtual void DebugFormat(string format, params object[] args)
        {
            WriteLine(ConsoleColor.Green, format, args);
        }
    }

    #endregion
}

And it's easy to use in a WinForms application:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    using (var webServer = new StaticWebServer())
    {
        webServer.RunAsync();
        Application.Run(new Views.MainView());
    }
}

from embedio.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.