Member-only story
In this blog, we will be exploring a code written in the Go programming language that serves a basic file browser over HTTP. This code is designed to run on a web server that serves files from a given directory and allows users to browse through the directory structure and view file details.
Let’s begin by understanding the structure of the code.
The code begins by importing the necessary packages for running an HTTP server and for reading and manipulating files.
The code defines a struct called File
which is used to store information about each file in the directory. It has fields for Name
, Size
, Mode
, ModTime
, and IsDir
.
The main
function sets up an HTTP server that listens on port 8080. When a request is received, it checks the URL path to determine the directory to browse. If no path is specified, it defaults to the current directory.
The code then reads the contents of the directory specified by the path using the ioutil.ReadDir
function. It then iterates over each file in the directory and creates an instance of the File
struct for each file, populating the fields with the file details.
package main
import (
"io/ioutil"
"net/http"
"os"
"text/template"
)
type File struct {
Name string
Size int64
Mode os.FileMode
ModTime string
IsDir bool
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path[1:]
if path == "" {
path = "."
}
files…