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

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

    Software Engineer | Ethical Hacker & Cybersecurity...

    Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.