go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/web/static.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package web
     9  
    10  import "net/http"
    11  
    12  // Static serves a static file from a given filesystem.
    13  //
    14  // It assumes views as the provider for failure conditions.
    15  func Static(ctx Context, fs http.FileSystem, path string) Result {
    16  	f, err := fs.Open(path)
    17  	if err != nil {
    18  		return ctx.Views().InternalError(err)
    19  	}
    20  	defer f.Close()
    21  	finfo, err := f.Stat()
    22  	if err != nil {
    23  		return ctx.Views().InternalError(err)
    24  	}
    25  	if finfo.IsDir() {
    26  		return ctx.Views().NotFound()
    27  	}
    28  	http.ServeContent(ctx.Response(), ctx.Request(), path, finfo.ModTime(), f)
    29  	return nil
    30  }