Use golang webserver, the root directory of the site where the file system mapping to?

In Go, net / http package to provide Web server functionality. This is not a static file server, it is far more than that.

No file system "root" concept. The Web server using handlers to provide an HTTP request is mapped to a URL. Handler is responsible for processing HTTP requests, and set and generating a response can register a handler, such as having the Handle () or HandleFunc () function You can use ListenAndServe () function to start the server.

Read the net / http package documentation, understand the basic concept and get started. It also contains many small examples.

Writing Web Applications blog post is also helpful.

Static file server

However, it provides static file server or "File System" feature, http package includes a FileServer () function, which returns Handler a deal with static files. You can specify the "root" folder as FileServer () parameters provide static file.

If you pass the absolute path to FileServer (), then there is no doubt what that means. If you provide a relative path, it is always interpreted in the context of the current or working directory. By default, this is the start of your application's files folder (file which you perform go run ... command folder or compiled executable binary files).

Example:

http.Handle("/", http.FileServer(http.Dir("/tmp")))

This sets a handler to provide the mapping to the root URL / folder file in / tmp example, in response to the GET request "/mydoc.txt" will be "/tmp/mydoc.txt" static file.

Complete application:

package main
import (
    "log"
    "net/http"
)
func main() {
    // Simple static webserver:
    http.Handle("/", http.FileServer(http.Dir("/tmp")))
    log.Fatal(http.ListenAndServe(":8080", nil))
}

You can use StripPrefix () function to perform more complex mapping example:

// To serve a directory on disk (/tmp) under an alternate URL
// path (/tmpfiles/), use StripPrefix to modify the request
// URL's path before the FileServer sees it:
http.Handle("/tmpfiles/",
    http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))

Guess you like

Origin www.cnblogs.com/enumx/p/12313114.html