user2873003
user2873003

Reputation: 356

Render css js img files in gorilla mux

Learning Gorilla Toolkit and golang so please go easy here. Would like to render .css, .js, and .jpeg files in their corresponding folders.

File Structure is:

ROOT/
 |--main.go, message.go
 |
 |Templates/
 |   |--index.html,confirmation.html
 |
 |Static/
   |
   |css/
   |--ex1.css, ex2.css
   |   
   |js/
   |--ex1.js, ex2.js
   |
   |Images/ 
   |--ex1.jpeg, ex2.jpeg

Package main with gorilla pat and mux as follows:

package main

import (
  "github.com/gorilla/mux"
  "github.com/gorilla/pat"
  "html/template"
  "log"
  "net/http"
)

func main() {

  r := pat.New()
  r.Get("/", http.HandlerFunc(index))
  r.Post("/", http.HandlerFunc(send))
  r.Get("/confirmation", http.HandlerFunc(confirmation))

  log.Println("Listening...")
  http.ListenAndServe(":8080",r)

  router := mux.NewRouter()
  router.HandleFunc("/", Home)
  router.PathPrefix("/static/").Handler(http.StripPrefix("/static/",http.FileServer(http.Dir(./static/))))
  http.Handle("/", router)
  err := http.ListenAndServe(":8443", router)
  if err != nil {
    log.Fatalln(err)
    }
}

Getting error:

.\main.go:23: syntax error: unexpected .

Not sure how to run multiple http servers through func main to start app and render all files nested in static folder.

Upvotes: 2

Views: 2102

Answers (1)

Alex Edwards
Alex Edwards

Reputation: 53

You should:

  • Make the parameter to http.Dir a string: http.Dir("./static/").
  • Run the first http.ListenAndServe in a separate Goroutine using the go command.
  • Remove the line http.Handle("/", router). This registers the Gorilla Mux router as the handler for / in the http.DefaultServeMux, which you then don't use at all. So it can be safely removed.

Like so:

package main

import (
    "github.com/gorilla/mux"
    "github.com/gorilla/pat"
    "log"
    "net/http"
)

func main() {

    r := pat.New()
    r.Get("/", http.HandlerFunc(index))
    // etc...

    log.Println("Listening on :8080...")
    go http.ListenAndServe(":8080", r)

    router := mux.NewRouter()
    router.HandleFunc("/", home)
    router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))

    log.Println("Listening on :8443...")
    http.ListenAndServe(":8443", router)
}

func index(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Index page"))
}

func home(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Home page"))
}

Upvotes: 2

Related Questions