Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static file server in Golang using gorilla/mux

I have made a app where I need to serve the same files to multiple routes because the front end is a React app. I have been using gorilla mux for the router. The file structure is as follows:

main.go
build/
  | index.html
  | service-worker.js
     static/
       |  js/
           | main.js
       |  css/
           | main.css

The files are refereed to assuming they are at the root of the file directory. So in the html file they are requested like '/static/js/main.js'.

In main my routes are defined as follows:

r.PathPrefix("/student").Handler(http.StripPrefix("/student",http.FileServer(http.Dir("build/")))).Methods("GET")
r.PathPrefix("/").Handler(http.FileServer(http.Dir("build/"))).Methods("GET")

This way I get the index.html file served in both the '/' and '/student' route. If I have them the other way around the '/student' path gets a 404 error. So what I am asking is there another way to serve the same content for both of these routes in order for me not have to define a route for each view I will have in my web app.

like image 655
Teodor Avatar asked Feb 05 '18 20:02

Teodor


People also ask

How do I serve static files in gorilla mux?

Using Gorilla Mux and the HTTP module in GoLang, we can serve static files directly from the file system. http. FileServer is the Handler that we can use to serve static files to the user. FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at the root.

What is Gorilla mux in GoLang?

Package gorilla/mux implements a request router and dispatcher for matching incoming requests to their respective handler. The name mux stands for "HTTP request multiplexer". Like the standard http. ServeMux , mux.

Why is gorilla mux used?

Gorilla Mux provides functionalities for matching routes, serving static files, building single-page applications (SPAs), middleware, handling CORS requests, and testing handlers. This tutorial will walk you through using the Gorilla Mux package as a router for your applications.

What is mux vars in GoLang?

The name mux stands for "HTTP request multiplexer". Like the standard http. ServeMux, mux. Router matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions.


1 Answers

I've had this exact setup on multiple occasions.

You will need a file server that serves all static assets. A file server to serve your index.html file on all unhandled routes. A (I assume) a sub router for all API calls to your server.

Here is an example that should match your file structure.

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()

    // Handle API routes
    api := r.PathPrefix("/api/").Subrouter()
    api.HandleFunc("/student", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "From the API")
    })

    // Serve static files
    r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./build/static/"))))

    // Serve index page on all unhandled routes
    r.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "./build/index.html")
    })

    fmt.Println("http://localhost:8888")
    log.Fatal(http.ListenAndServe(":8888", r))
}
like image 186
jmaloney Avatar answered Sep 21 '22 12:09

jmaloney