github.com/aarzilli/tools@v0.0.0-20151123112009-0d27094f75e0/net/http/tplx/tpl_from_dsfs.go (about)

     1  package tplx
     2  
     3  import (
     4  	"bytes"
     5  	"net/http"
     6  	"sync"
     7  
     8  	"github.com/pbberlin/tools/net/http/loghttp"
     9  	"github.com/pbberlin/tools/os/fsi/dsfs"
    10  	"github.com/pbberlin/tools/os/fsi/memfs"
    11  	"google.golang.org/appengine"
    12  )
    13  
    14  const TplPrefix = "/mnt02"
    15  const pathToTmpl = "/page/programmatic_content/index.html"
    16  
    17  var fs1 = memfs.New(
    18  	memfs.Ident(TplPrefix[1:]), // a closured variable in init( ) did not survive map-pointer reallocation
    19  )
    20  
    21  // Implements fsi.File
    22  type SyncedMap struct {
    23  	sync.Mutex
    24  	mp map[string]string
    25  }
    26  
    27  // We need this, since we have that additional step of putting the {{ .Variable }} strings into the hugo html
    28  var mp = SyncedMap{mp: map[string]string{}}
    29  
    30  func TemplateFromHugoReset(w http.ResponseWriter, r *http.Request, mapOnerous map[string]interface{}) {
    31  	r.Header.Set("X-Custom-Header-Counter", "nocounter")
    32  
    33  	mpOld := mp
    34  	mpOld.Lock()
    35  	if _, ok := mp.mp[pathToTmpl]; ok {
    36  		mp = SyncedMap{mp: map[string]string{}}
    37  	}
    38  	mpOld.Unlock()
    39  	w.Write([]byte("reset successful"))
    40  }
    41  
    42  func TemplateFromHugoPage(w http.ResponseWriter, r *http.Request) string {
    43  
    44  	mp.Lock()
    45  	if tpl, ok := mp.mp[pathToTmpl]; ok {
    46  		mp.Unlock()
    47  		return tpl
    48  	}
    49  	mp.Unlock()
    50  
    51  	lg, _ := loghttp.BuffLoggerUniversal(w, r)
    52  
    53  	//
    54  	fs2 := dsfs.New(
    55  		dsfs.MountName(TplPrefix[1:]),
    56  		dsfs.AeContext(appengine.NewContext(r)),
    57  	)
    58  	fs1.SetOption(
    59  		memfs.ShadowFS(fs2),
    60  	)
    61  
    62  	bts, err := fs1.ReadFile(pathToTmpl)
    63  	if err != nil {
    64  		lg(err)
    65  		bts = hugoTplFallback
    66  	}
    67  
    68  	bts = bytes.Replace(bts, []byte("[REPLACE_TITLE]"), []byte("{{ .HtmlTitle }}"), -1)
    69  	bts = bytes.Replace(bts, []byte("[REPLACE_DESC]"), []byte("{{ .HtmlDescription }}"), -1)
    70  	bts = bytes.Replace(bts, []byte("</head>"), []byte("{{ .HtmlHeaders }}\n</head>"), -1)
    71  	bts = bytes.Replace(bts, []byte("<p>[REPLACE_CONTENT]</p>"), []byte("{{ .HtmlContent }}"), -1)
    72  	bts = bytes.Replace(bts, []byte("[REPLACE_CONTENT]"), []byte("{{ .HtmlContent }}"), -1)
    73  	bts = bytes.Replace(bts, []byte("<span id='REPLACE_FOOTER'></span>"), []byte("{{ .HtmlFooter }}"), -1)
    74  
    75  	mp.Lock()
    76  	mp.mp[pathToTmpl] = string(bts)
    77  	mp.Unlock()
    78  
    79  	return mp.mp[pathToTmpl]
    80  
    81  }