github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/net/http/static/static.go (about)

     1  // Package static provides a handler for serving static assets from an in-memory
     2  // map.
     3  package static
     4  
     5  import (
     6  	"net/http"
     7  	"strings"
     8  	"time"
     9  )
    10  
    11  // use start time as a conservative bound for last-modified
    12  var lastMod = time.Now()
    13  
    14  type Handler struct {
    15  	Assets map[string]string
    16  
    17  	// Index is the name of an entry in Assets that should be used if the request
    18  	// path is empty (equivalent to requesting "/"). This is analogous to index
    19  	// documents commonly used in webservers. If Index is empty, it will be
    20  	// ignored.
    21  	Index string
    22  
    23  	// Default is the name of an entry in Assets that should be used if the
    24  	// the requested path does not exist in Assets. This is useful for
    25  	// delivering a common document (usually a frontend application script) that
    26  	// handles URL-based state on the client side. If Default is empty, it will be
    27  	// ignored.
    28  	Default string
    29  }
    30  
    31  func (h Handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
    32  	output, ok := h.Assets[r.URL.Path]
    33  	if !ok && r.URL.Path == "" && h.Index != "" {
    34  		output = h.Assets[h.Index]
    35  	} else if !ok && h.Default != "" {
    36  		output = h.Assets[h.Default]
    37  	} else if !ok {
    38  		http.NotFound(rw, r)
    39  		return
    40  	}
    41  
    42  	// Some autogenerated documentation uses frames, e.g. Javadoc
    43  	rw.Header().Set("X-Frame-Options", "SAMEORIGIN")
    44  
    45  	http.ServeContent(rw, r, r.URL.Path, lastMod, strings.NewReader(output))
    46  }