Serve File
Kegunaan file server adalah untuk menampilkan suatu file yang ada dalam satu direktori yang sama dengan aplikasi.
Contoh code penggunaan file server
package main
import (
"fmt"
"net/http"
)
func main() {
mux := http.NewServeMux()
// menampilkan file berdasarkan direktori (index.html yang utama)
fs1 := http.FileServer(http.Dir("files/html"))
fs2 := http.FileServer(http.Dir("files/html2"))
fs3 := http.FileServer(http.Dir("files/txt"))
mux.Handle("/", fs1)
// jika didepan / ada tambahan kata, harus dihapus dengan http.StripPrefix
mux.Handle("/html", http.StripPrefix("/html", fs2))
mux.Handle("/txt", http.StripPrefix("/txt", fs3))
server := http.Server{
Addr: "localhost:5000",
Handler: mux,
}
fmt.Println("Server running on", server.Addr)
err := server.ListenAndServe()
if err != nil {
panic(err)
}
}



Contoh code penggunaan serve file
Struktur file dalam direktori ./file, ./file/html dan ./file/txt.

Last updated