Where is the filesystem "root" of a golang webserver. It doesn't seem to be in the directory the executable is in. By "root" I mean the directory I would use for, say, the src attribute of an img, without any path. I don't plan to do this, but it would help me understand the structure if I knew
相关问题
- Golang mongodb aggregation
- How to flatten out a nested json structure in go
- how to install private repo using glide golang
- How to convert a string to a byte array which is c
- Web server farms with IIS ? Basic Infos [closed]
相关文章
- WebService 启动调试后,能成功调用函数,但断点进不去任何方法
- Can I run a single test in a suite?
- How to check if a request was cancelled
- Is it possible to implement an interface with unex
- How to access value of first index of array in Go
- Embedded Interface
- How to represent an array with mixed types
- go tutorial select statement
Introduction
In Go the
net/http
package is used to provide Web Server functionality. This is not a static fileserver, it is much more than that.There is no filesystem "root" concept. The provided web server uses handlers to serve HTTP requests which are mapped to URLs. A handler is responsible to process an HTTP request and to setup and generate the response. A handler can be registered e.g. with the
Handle()
orHandleFunc()
functions. The server can be started with theListenAndServe()
function.Read the package documentation of
net/http
to understand the basic concepts and to get started. It also contains many small examples.The Blog article Writing Web Applications is also helpful.
Static File Server
However, a static file server or "filesystem" functionality is provided, there is a
FileServer()
function in thehttp
package which returns aHandler
which serves static files. You can specify the "root" folder to serve static files from as a parameter ofFileServer()
.If you pass an absolute path to
FileServer()
, then there is no question 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 folder you start the application from (the folder you're in when executing thego run ...
command or the compiled executable binary).Example:
This will setup a handler to serve files from the folder
/tmp
mapped to the root URL/
. For example the response to the GET request"/mydoc.txt"
will be the"/tmp/mydoc.txt"
static file.Complete application:
You can do more complex mapping using the
StripPrefix()
function. Example: