The last article on the Go template library application left us with a problem. The page template is a BootStrap CSS, JS file referenced by the CDN. So far our server has not been able to respond to static file requests from clients by sending files on the server’s disk to clients. If you have used and configured an Nginx server, you must know that Nginx naturally supports access to static resources. No, in the first article we stated that “Go builds and starts a highly concurrent HTTP server without relying on any third party components.” This article takes a look at how to handle static resource requests using the Go language’s NET/HTTP library.

Let’s start with a simple example of how to create a static resource server using NET/HTTP before applying it to our http_demo project.

The source code for each article in the Go Web Programming series is printed with a corresponding version of the package for your reference. Get the source code of this article by replying to gohttp08

Create a static resource server

We will create a new main.go to store the code for creating the static resource server and listening for requests. At the same time, we will create assets/ CSS and Assets/JS directories in the same directory to store the static files used by the page template of the previous article.

└. Go assets/ ├ ─ ├ ─ class-impCopy the code

The code in main.go is as follows:

package main

import "net/http"

func main(a) {
    fs := http.FileServer(http.Dir("assets/"))
    http.Handle("/static/", http.StripPrefix("/static/", fs))

    http.ListenAndServe(": 8080".nil)}Copy the code
  • First we usehttp.FileServerCreates a content response for all using the given file systemHTTPThe handler of the request.
  • http.Handle("/static/", http.StripPrefix("/static/", fs))Let the file server use itassetsFile response under directoryURLPath to/static/All at the beginningHTTPThe request.
  • assetsThe root directory of the file system that is set to the file server/staticAt the beginning ofURLRequest, so we need to usehttp.StripPrefix()thestaticThe prefix has to be removedassetsThe requested file was found in the directory.

Using cURL to request the CSS file, see if it works.

$ go run main.go

$ curl -s http://localhost:8080/static/css/bootstrap.min.css

/*!
 * Bootstrap v3.3.7 (http://getbootstrap.com)
 * Copyright 2011-2016 Twitter, Inc.
 ......

Copy the code

In combination withgorillia/muxUsing a File Server

The file server handler in the example above is registered to the standard ServeMux (service multiplexer) provided by the NET/HTTP library. Our HTTP_demo project uses the Gorillia/MUx library service multiplexer to support complex route registration. The two work differently, so applying the file server to our project requires some tweaking to make it work.

First let’s copy the entire assets directory into the root directory of the project.

func RegisterRoutes(r *mux.Router) {
   // serve static file request
   fs := http.FileServer(http.Dir("assets/"))
   serveFileHandler := http.StripPrefix("/static/", fs)
   r.PathPrefix("/static/").Handler(serveFileHandler)
   ......
}
Copy the code
  • userouter.PathPrefix("/static")Create a match there/staticPrefix request route.
  • Then use theroute.HandlerMethod to register the file server as a handler for the route (Handleris*mux.RouteOn the method).

After registering the file server, we replaced the JS and CSS files on the CDN referenced by the page template with the file links on our server.

<html lang="en">
<head>.<link href="/static/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

{{ template "nav" .}}

<div class="container">
    {{template "content" .}}
</div> <! -- /container -->

<script src="/static/js/bootstrap.min.js"></script>
</body>
</html>
Copy the code

, and then restart the server before the page HTTP: localhost: / view/index, verify whether our server is now to the request of the servo static files.

Page style is normal, now as long as the server the assets directory file, we can all through the URL to access http://localhost:8000/static/ * path.

The source code of today’s article has been packaged and uploaded. Please reply to gohttp08 to get the download link. If this article helps you, don’t forget to share it with more people. Pay attention to the public account for the first time every week to get the latest articles.

These reviews

Learn more about writing HTTP servers with Go

Use the Gorilla/MUx router

Go Web Programming – Apply the database

Go Web Programming – Learn in depth how to parse HTTP requests

Go Web Programming – an ultra-detailed template library application guide