Standard library / net/http

http.FileServerFS()

Serves an fs.FS containing seekable files; available since Go 1.22. Expected stdout: '200 hello\n'.

Formal Syntax & Structure

go syntaxgo
func FileServerFS(root fs.FS) Handler

Parameters & Attributes

NameTypeDescription
rootfs.FSInput value of the declared type; see the usage example.

Return Value

Handler

Operation result; check errors and validity indicators when returned.

Working Example

Example Snippetgo
package main
import (  "bufio"  "crypto/x509"  "encoding/pem"  "errors"  "fmt"  "io"  "net"  "net/http"  "net/http/httptest"  "os"  "path/filepath"  "testing/fstest"  "time")
func main() {  w := httptest.NewRecorder()  http.FileServerFS(files()).ServeHTTP(w, httptest.NewRequest("GET", "/demo.txt", nil))  fmt.Println(w.Code, w.Body.String())}func hello(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }func fixture() *httptest.Server                    { return httptest.NewServer(http.HandlerFunc(hello)) }func files() fstest.MapFS                          { return fstest.MapFS{"demo.txt": &fstest.MapFile{Data: []byte("hello")}} }func disk() (string, func()) {  d := must(os.MkdirTemp("", "bytemind-"))  check(os.WriteFile(filepath.Join(d, "demo.txt"), []byte("hello"), 0600))  return d, func() { check(os.RemoveAll(d)) }}
// Test-only TLS credential, supplied by httptest. Never deploy this key.func tlsRound(usePackage bool) {  seed := httptest.NewTLSServer(http.HandlerFunc(hello))  defer seed.Close()  d, clean := disk()  defer clean()  pair := seed.TLS.Certificates[0]  certFile := filepath.Join(d, "cert.pem")  keyFile := filepath.Join(d, "key.pem")  check(os.WriteFile(certFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: pair.Certificate[0]}), 0600))  key := must(x509.MarshalPKCS8PrivateKey(pair.PrivateKey))  check(os.WriteFile(keyFile, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: key}), 0600))  l := must(net.Listen("tcp4", "127.0.0.1:0"))  defer l.Close()  s := &http.Server{Handler: http.HandlerFunc(hello), ReadHeaderTimeout: time.Second}  done := make(chan error, 1)  go func() {    if usePackage {      done <- http.ServeTLS(l, http.HandlerFunc(hello), certFile, keyFile)    } else {      done <- s.ServeTLS(l, certFile, keyFile)    }  }()  c := seed.Client()  c.Timeout = 3 * time.Second  res := must(c.Get("https://" + l.Addr().String()))  fmt.Println(string(must(io.ReadAll(res.Body))), res.TLS != nil)  check(res.Body.Close())  if usePackage {    check(l.Close())    <-done  } else {    check(s.Close())    if e := <-done; !errors.Is(e, http.ErrServerClosed) {      panic(e)    }  }}func hijack(controller bool) {  s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {    var c net.Conn    var b *bufio.ReadWriter    var e error    if controller {      c, b, e = http.NewResponseController(w).Hijack()    } else {      c, b, e = w.(http.Hijacker).Hijack()    }    check(e)    defer c.Close()    check(c.SetDeadline(time.Now().Add(time.Second)))    _, e = b.WriteString("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok")    check(e)    check(b.Flush())  }))  defer s.Close()  res := must(s.Client().Get(s.URL))  defer res.Body.Close()  fmt.Println(string(must(io.ReadAll(res.Body))))}
func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference