Skip to content

Instantly share code, notes, and snippets.

@maxk42
Last active January 16, 2022 01:08
Show Gist options
  • Save maxk42/c70fa39c09714bb48744 to your computer and use it in GitHub Desktop.
Save maxk42/c70fa39c09714bb48744 to your computer and use it in GitHub Desktop.
Serving static and dynamic content together in golang
// This assumes your web app is running in a directory which has a subdirectory named 'public/' and
// that there is an 'img/' subdirectory in 'public/' containing an image named 'kitten.jpg'
package main
import (
"fmt"
"net/http"
)
func index_handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<html><body>Hi world.<img src=\"img/kitten.jpg\"></body></html>")
}
func main() {
fmt.Println("Running...")
http.Handle("/img", http.FileServer(http.Dir("public/img")))
http.Handle("/js", http.FileServer(http.Dir("public/js")))
http.Handle("/css", http.FileServer(http.Dir("public/css")))
http.HandleFunc("/", index_handler)
http.ListenAndServe(":9000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment