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

Published on January 31, 2020 26 sec read

HIRE US 🖐
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.

    main.go
    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
    http://localhost/static/css/styles.css
    // images
    http://localhost/static/images/logo.png
    

    Author

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

    Follow

    Leave a Reply

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