Standard library / net/http

http.NewFileTransport()

Create a transport from an http.FileSystem. File access is governed by that filesystem, not by URL host; use only a restricted synthetic filesystem here. Expected stdout: 'hello\n'.

Formal Syntax & Structure

go syntaxgo
func NewFileTransport(fs FileSystem) RoundTripper

Parameters & Attributes

NameTypeDescription
fsFileSystemFile system to serve through the transport.

Return Value

RoundTripper

Operation result; check errors and validity indicators when returned.

Working Example

Example Snippetgo
package main
import (  "fmt"  "io"  "net/http"  "testing/fstest")
func main() {  rt := http.NewFileTransport(http.FS(fstest.MapFS{"demo.txt": {Data: []byte("hello")}}))  r := must(rt.RoundTrip(must(http.NewRequest("GET", "file:///demo.txt", nil))))  defer r.Body.Close()  fmt.Println(string(must(io.ReadAll(r.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