Last active
January 16, 2022 01:08
-
-
Save maxk42/c70fa39c09714bb48744 to your computer and use it in GitHub Desktop.
Serving static and dynamic content together in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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