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

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.

主站蜘蛛池模板: 浏阳市| 涞源县| 嘉定区| 武夷山市| 交口县| 大邑县| 太仓市| 钟山县| 顺义区| 横峰县| 乃东县| 沁源县| 苏州市| 特克斯县| 涡阳县| 六枝特区| 甘谷县| 宜州市| 贵阳市| 普格县| 龙陵县| 普定县| 建水县| 得荣县| 建始县| 孟津县| 广安市| 金沙县| 江津市| 故城县| 景泰县| 仁化县| 淳化县| 苍梧县| 同江市| 盐池县| 蚌埠市| 衡水市| 蒲城县| 房山区| 吉安县|