1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
package main
import ( "embed" "fmt" "net/http" "strings" )
var staticFiles embed.FS
func main() { serveIndexPage() addAllAssets("static") fmt.Println("Listen:8083...") err := http.ListenAndServe(":8083", nil) if err != nil { fmt.Println(err.Error()) } }
func serveIndexPage() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { indexHTML, err := staticFiles.ReadFile("static/index.html") if err != nil { fmt.Println(err.Error()) return } fmt.Fprint(w, string(indexHTML)) }) }
func addAllAssets(rootPath string) { files, err := staticFiles.ReadDir(rootPath) if err != nil { panic(err) } for _, file := range files { if file.IsDir() { addAllAssets(rootPath + "/" + file.Name()) continue } filePath := rootPath + "/" + file.Name() http.HandleFunc(strings.Replace(filePath, "static", "", 1), handleAssets(filePath)) } }
func handleAssets(filePath string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { indexHTML, err := staticFiles.ReadFile(filePath) if err != nil { fmt.Println(err.Error()) return } if strings.Contains(filePath, ".html") { w.Header().Set("content-type", "text/html; chatset=utf-8") } if strings.Contains(filePath, ".js") { w.Header().Set("content-type", "application/javascript") } if strings.Contains(filePath, ".css") { w.Header().Set("content-type", "text/css") } if strings.Contains(filePath, ".png") { w.Header().Set("content-type", "image/png") } if strings.Contains(filePath, ".txt") { w.Header().Set("content-type", "text/plain") } fmt.Fprint(w, string(indexHTML)) } }
|
v1.5.2