Building the simple static file server in minutes

Sometimes, as part of the API, we should serve static files. The other application of httprouter is building scalable file servers. It means that we can build a Content Delivery Platform of our own. Some of the clients need static files from the server. Traditionally, we use Apache2 or Nginx for that purpose. But, from within the Go server, in order to serve the static files, we need to route them through a universal route like this:

/static/*

See the following code snippet for our implementation. The idea is to use the http.Dir method to load the filesystem, and then use the ServeFiles function of the httprouter instance. It should serve all the files in the given public directory. Usually, static files are kept in the folder /var/public/www on a Linux machine. Since I am using OS X, I create a folder called static in my home directory:

mkdir /users/naren/static

Now, I copy the Latin.txt and Greek.txt files, which we created for the previous example, to the preceding static directory. After doing this, let us write the program for the file server. You will be amazed at the simplicity of httprouter. Create a program called fileserver.go:

package main
import (
"github.com/julienschmidt/httprouter"
"log"
"net/http"
)
func main() {
router := httprouter.New()
// Mapping to methods is possible with HttpRouter
router.ServeFiles("/static/*filepath",
http.Dir("/Users/naren/static"))
log.Fatal(http.ListenAndServe(":8000", router))
}

Now run the server and see the output:

go run fileserver.go

 Now, let us open another terminal and fire this CURL request:

http://localhost:8000/static/latin.txt
Now, the output will be a static file content server from our file server:
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.190.211