How to Load Static Files (CSS, Images, etc) in Go

Published on January 31, 2020 26 sec read

We're available to do freelance project. Take a look at our services!

Today, we’re going to learn how to load static files in Go. We’ll access to CSS & image from our application.

Table of Contents

  1. Project Structure
  2. Load Files

Project Structure

This is our project’s folder structure:

  • project
    • assets
      • css
        • styles.css
      • images
        • logo.png
    • main.go

  • Load Files

    We’ll use http.FileServer function to load the assets files and http.Handle function to set prefix.

    package main
    import "net/http"
    func main() {
        fs := http.FileServer(http.Dir("assets/"))
        http.Handle("/static/", http.StripPrefix("/static/", fs))
        http.ListenAndServe(":80", nil)

    If we run the project, the project will run on port 80. After running the project, we can access the CSS and images like:

    // css
    // images

    Monthly Newsletter

    One email a month, packed with the latest tutorials, delivered straight to your inbox.
    We'll never send any spam or promotional emails.

    Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.


    Leave a Reply

    Your email address will not be published. Required fields are marked *