With a Go web server, where is the root of the site displayed on the file system?

Where is the "root" file system of the Go net/http web server. It does not seem to be in the directory where the executable is located. By β€œroot” I mean a directory that I would use, say, for the src img attribute, without any path. I do not plan to do this, but it would help me understand the structure if I knew.

+9
go webserver
source share
1 answer

Introduction

Go uses the net/http package to provide web server functionality. This is not a static file server, it is much more.

There is no concept of a β€œroot” file system. The provided web server uses handlers to serve HTTP requests mapped to URLs. The handler is responsible for processing the HTTP request, as well as for setting up and generating the response. A handler can be registered, for example, with the functions Handle() or HandleFunc() . The server can be started using the ListenAndServe() function.

Read the net/http documentation for a basic understanding and getting started. It also contains many small examples.

Also useful is a blog article Writing Web Applications .

Static file server

However, the functions of a static file server or β€œfile system” are provided; in the http package there is a FileServer() function that returns a Handler that serves static files. As the parameter FileServer() you can specify the root folder for serving static files.

If you pass the absolute path to FileServer() , then there is no question what this means. If you specify a relative path, it is always interpreted in the context of the current or working directory. By default, this is the folder from which you start the application (the folder in which you run the go run ... command or the compiled executable file).

Example:

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

This will install a handler for serving files from the /tmp folder associated with the root URL / . For example, the response to a GET request "/mydoc.txt" would be a static file "/tmp/mydoc.txt" .

Fill out an 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 make a more complex display using the StripPrefix() function. Example:

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

All Articles