DEV Community

Rajdeep Das
Rajdeep Das

Posted on • Originally published at rajdeep-das.Medium on

Build a simple fileserver in 1 line using go


Photo by imgix on Unsplash

You have probably heard that Go is fantastic for building web applications of all shapes and sizes. This is partly due to the fantastic work that has been put into making the standard library clean, consistent, and easy to use.

If you’re just starting with web development in Go, the net/http package is super important. It helps you create servers for the web using simple and powerful building blocks.

The http.Handler Interface

As you become more familiar with Go, you will notice how much of an impact interfaces make in the design of your programs. The net/http interface encapsulates the request-response pattern in one method:

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}
Enter fullscreen mode Exit fullscreen mode

Implementors of this interface are expected to inspect and process data coming from the http.Request object and write out a response to the http.ResponseWriter object.

The http.ResponseWriter interface looks like this:

type ResponseWriter interface {
    Header() Header
    Write([]byte) (int, error)
    WriteHeader(int)
}
Enter fullscreen mode Exit fullscreen mode

Often, you just want to share simple web pages with pictures and styles. Imagine you have a basic webpage with text, images, and design, and you just want to show it to others on the internet. That’s where serving static files comes in handy.

package main

import (
 "fmt"
 "net/http"
)

func main() {
 fmt.Println("FileServer Stared on Port : 8080")
 // "." - current directory where the progam is running
 http.ListenAndServe(":8080", http.FileServer(http.Dir("."))) 
}
Enter fullscreen mode Exit fullscreen mode

The http.ListenAndServe function is used to start the server, it will bind to the address we gave it (:8080) and when it receives an HTTP request, it will hand it off to the http.Handler that we supply as the second argument. In our case, it is the built-in http.FileServer.

The http.FileServer function builds an http.Handler that will serve an entire directory of files and figure out which file to serve based on the request path. We told the FileServer to serve the current working directory with http.Dir(".").

If we go to localhost:8080/main.go in our web browser, we’ll see what’s inside our main.go file. With just one line of Go code, we can run this program from any folder and turn our computer into a simple server that shares files, like a tree of files, with others.

Checkout the project — Rajdeep-Das/go-networking: Go Lang Networking Stand Lib & Cloud Native Networking Projects (github.com)

Happy reading 📖. 😃

Top comments (0)