Golang serving static files, please explain what happens in these 3 lines of code

golang serve static files
go httpclient
golang http response body
parsemultipartform
golang http cookie
golang mux
golang parseform
formvalue golang

I'm learning go web programming and understand everthing but I'm getting lost in this 3 apparently simple lines:

fs := http.FileServer(http.Dir("public"))
handler := http.StripPrefix("/static/", fs)
mux.Handle("/static/", handler)

...I have read the go src for the following lines and this is what I can infer:

  1. http.Dir("public") is casting string "public" to type Dir.
  2. then we serve a file (including all its content) with http.FileServer()
  3. We strip prefix because now we are inside a handleFunc() for fs
  4. StripPrefix() created a HandlerFunc()
  5. mux.Handle() registers HandlerFunc() in the mux.
  6. Deep goes the rabbit hole... and then this goroutine go c.serve(ctx) by func (srv *Server) Serve(l net.Listener) error {}
  7. So each static file inside /public/ dir is served concurrently by our server.

Can someone confirm or explain what exactly is happening in the 3 lines of code.

After looking at the docs I think this is what happens:

http.Dir("public")

you are converting the string "public" to the type Dir which implements the FileSystem interface

fs := http.FileServer(http.Dir("public"))

which according to the docs does:

FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root.

root being the Dir you are passing as a parameter

handler := http.StripPrefix("/static/", fs)

you wrap the Handler fs in the Handler created by the StripPrefix func

which according to the docs does:

StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h

h being the Handler fs you are passing as a parameter

mux.Handle("/static/", handler)

you let all requests starting with the path /static/ be handled by handler

So in short all requests for the the path /static/ will get stripped of the /static/ prefix and will return a file from the public directory on you server with the same name, eg. a request to /static/requestedFile.txt will return the file under public/requestedFile.txt

Golang serving static files, please explain what is happening in , Can someone confirm or explain what exactly is happening in the 3 lines of code. We will create a simple “app”, which will serve a different kind of files with respect to their types. Creating App’s Architecture. First things first. To get started, create a new folder for a project and a few subfolders in the folder where you keep your Golang programs: mkdir golang-blog && cd golang-blog mkdir src && mkdir bin

Currently going through a GoLang tutorial by Soham Kamani, and found that his explanation helps a ton:

func newRouter() *mux.Router {
    r := mux.NewRouter()
    r.HandleFunc("/hello", handler).Methods("GET")

    // Declare the static file directory and point it to the
    // directory we just made
    staticFileDirectory := http.Dir("./assets/")

    // Declare the handler, that routes requests to their respective filename.
    // The fileserver is wrapped in the `stripPrefix` method, because we want to
    // remove the "/assets/" prefix when looking for files.
    // For example, if we type "/assets/index.html" in our browser, the file server
    // will look for only "index.html" inside the directory declared above.
    // If we did not strip the prefix, the file server would look for
    // "./assets/assets/index.html", and yield an error
    staticFileHandler := http.StripPrefix("/assets/", http.FileServer(staticFileDirectory))

    // The "PathPrefix" method acts as a matcher, and matches all routes starting
    // with "/assets/", instead of the absolute route itself
    r.PathPrefix("/assets/").Handler(staticFileHandler).Methods("GET")
    return r
}

Serving Static Files, Now let's improve the look and feel of the home page by adding some static CSS and image FileServer handler which you can use to serve files over HTTP from a specific directory. Open your main.go file and add the following code, so that the file ends up looking like this: If you want to do this for all directories under . goreporter. A Golang tool that does static analysis, unit testing, code review and generate code quality report. Template. html template file which can be loaded via -t <file>.

Confirming:

You are registering an automatic handler for static files. Requests in the form: GET /static/some_file will be handled concurrently by delivering files from the /public directory.

Write a Lightweight API and Static File Server in Go, Without this, Go wouldn't know what to do when you compile and run this file. As you probably Line 3 demonstrates how to import multiple libraries. The first thing to mention is that types in Go are defined after the identifier, as in: With that done, we just have to add the code to serve static files. Serving Static Files. Now that we’ve had a look at the asynchronous nature of a Go based web server, we can move on to serving some static files. First, create a static folder within your project’s directory and then create some simple HTML files. For this example I’m just serving back the following:

Frequently Asked Questions (FAQ), Within a few days the goals had settled into a plan to do something and a fair idea of what it would be. A blog post about the gopher explains how it was derived from one she used for a efficient execution, or ease of programming; all three were not available in the This last line of this code sample does not compile. If a package grows so much that I need to split it into several directories to handle my code (go allows to split it into multiple files in one directory), then I would think about my code organization. Large functions, types (classes in other languages), files, or packages tend to become hard to maintain.

proposal: cmd/go: support embedding static assets (files) in binaries , There are many tools to embed static asset files into binaries: gopherbot added this to the Proposal milestone on Dec 3, 2019 Dir) without changing the code, and the final implementation is quite versatile, Edit it might need a single package mypackagename line at the top, like a go file would have. Handle static files in Golang is very straightforward just one line of code to do this: http.Handle("/", http.StripPrefix(strings.TrimRight(path, "/"), http.FileServer(http.Dir(directory)))) where path is http path and directory is the static directory you want to serve over http

Cache-Control headers for static files using ServeFiles · Issue #40 , I am not sure how to do this is there support for this? 3 simple arguments and all the work in julienschmidt/httprouter: It's perfect to serve the assets of a simple website, with a single line of code. For the actual usage of ServeFiles , no matter, it can't go wrong. I'd like to discuss if your down for that. So while it's fresh in my head, here's an explanation of principles behind creating and serving static sites with Go. Let's begin with a simple but real-world example: serving vanilla HTML and CSS files from a particular location on disk. Start by creating a directory to hold the project: $ mkdir static-site $ cd static-site