官术网_书友最值得收藏!

Building a simple static file server in minutes

Sometimes, an API can serve files. The other application of httprouter, apart from routing, is building an efficient file server. It means that we can build a content delivery platform of our own. Some clients need static files from the server. Traditionally, we use Apache2 or Nginx for that purpose. If one has to create something similar purely in Go, they can leverage httprouter.

Let us build one. From the Go server, in order to serve the static files, we need to route them through a universal route, like this:

/static/*

The plan is to use http package's Dir method to load the filesystem, and pass filesystem handler it returns to httprouter. We can use the ServeFiles function of the httprouter instance to attach a router to the filesystem handler. It should serve all the files in the given public directory. Usually, static files are kept in the /var/public/www folder on a Linux machine. Create a folder called static in your home directory:

mkdir -p /users/git-user/static

Now, copy the Latin.txt and Greek.txt files, which we created for the previous example, to the preceding static directory. After doing that, let us write the program for the file server using the following steps. You will be amazed at the simplicity of httprouter:

  1. Create a program at the following path:
touch -p $GOPATH/src/github.com/git-user/chapter2/fileServer/main.go
  1. Update the code like the following. You have to add a route that links a static file path route to a filesystem handler:
package main

import (
"log"
"net/http"

"github.com/julienschmidt/httprouter"
)

func main() {
router := httprouter.New()
// Mapping to methods is possible with HttpRouter
router.ServeFiles("/static/*filepath",
http.Dir("/Users/git-user/static"))
log.Fatal(http.ListenAndServe(":8000", router))
}

  1. Now run the server and see the output:
go run $GOPATH/src/github.com/git-user/chapter2/fileServer/main.go
  1. Open another Terminal and fire this curl request:
http://localhost:8000/static/latin.txt
  1. 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.

In the next section, we discuss about a widely used HTTP router called gorilla/mux.

主站蜘蛛池模板: 马鞍山市| 白河县| 乡城县| 宁南县| 当阳市| 安西县| 曲沃县| 南溪县| 木里| 义乌市| 弥渡县| 红桥区| 南乐县| 习水县| 台湾省| 甘孜| 香港| 昌黎县| 平顶山市| 正安县| 麦盖提县| 永胜县| 晋州市| 巴楚县| 巨鹿县| 五家渠市| 额济纳旗| 彩票| 于田县| 盐津县| 崇左市| 麻城市| 辰溪县| 福州市| 屏边| 应城市| 海南省| 原平市| 岫岩| 荥经县| 阿荣旗|