Examples

Go File Server

Building a File Server

Go file server serves static files with http.FileServer.

Introduction to Go File Server

The http.FileServer function in Go is a simple and efficient way to serve static files such as images, CSS, JavaScript, and HTML. This built-in function handles HTTP requests for static files and serves them to the client without requiring a complex setup.

Setting Up a Simple File Server

To set up a basic file server in Go, you need to utilize the http.FileServer and http.Handle functions. The following example demonstrates how to serve files from a directory called static.

Explaining the Code

  • http.Dir("./static"): Specifies the directory from which files will be served.
  • http.FileServer: Wraps the directory with a file server handler.
  • http.Handle("/", fs): Registers the file server handler to serve files at the root URL.
  • http.ListenAndServe(":8080", nil): Starts the server on port 8080.

Customizing URL Paths

You can customize the URL path by modifying the http.Handle function. For instance, to serve files under the URL path /static/, you would set it up as follows:

Security Considerations

When serving static files, be mindful of security concerns such as directory traversal attacks. Ensure that user inputs are sanitized and that you only expose the necessary files and directories.

Additionally, consider setting appropriate HTTP headers for caching, MIME types, and security purposes.

Conclusion

Using Go's http.FileServer makes it straightforward to serve static content efficiently. With minimal setup, you can have a file server running, handling client requests for static assets seamlessly. Remember to take care of security best practices to protect your server.