package app import ( "bytes" "fmt" "io" "log" "net/http" "path/filepath" "slices" "strings" "github.com/yosssi/gcss" ) var gcssCompileCache = make(map[string]string) const jobSpritesheetName = "jobs.gcss" func compileGCSS(reader io.Reader) (string, error) { compileBuf := bytes.Buffer{} if _, err := gcss.Compile(&compileBuf, reader); err != nil { return "", err } return compileBuf.String(), nil } func compileJobSpritesheetGCSS() error { jobs, err := getFormChoices("jobs") if err != nil { return err } slices.Sort(jobs) var gcss strings.Builder gcss.WriteString(".input-checkbox-choice.from-jobs, .input-radio-choice.from-jobs\n") for i, job := range jobs { gcss.WriteString(fmt.Sprintf(" input[value=%s] + label\n background-position-x: %dpx\n", job, -(i * 76))) } gcssCompileCache[jobSpritesheetName], err = compileGCSS(strings.NewReader(gcss.String())) return err } func httpServeCompiledGCSS(w http.ResponseWriter, name string) { w.Header().Add("Content-Type", "text/css") w.Header().Set("Cache-Control", "public, max-age=3600") w.WriteHeader(200) io.WriteString(w, gcssCompileCache[name]) } func httpBaseHandleGCSS(w http.ResponseWriter, r *http.Request, path []string) bool { // check path file := path[len(path)-1] fileExt := filepath.Ext(file) if fileExt != ".css" && fileExt != ".gcss" { return false } file = strings.TrimSuffix(file, fileExt) + ".gcss" // serve already compiled gcss > css if gcssCompileCache[file] != "" { httpServeCompiledGCSS(w, file) return true } log.Printf(" >> compile %s", file) // job sprite sheet if file == jobSpritesheetName { if err := compileJobSpritesheetGCSS(); err != nil { log.Println(" >> GCSS Error: ", err) httpHandleErrorText(w, err) return true } httpServeCompiledGCSS(w, file) return true } // read gcss file gcssReader, err := staticFS.Open(filepath.Join(staticEmbedPath, file)) if err != nil { httpHandleErrorText(w, err) return true } defer gcssReader.Close() gcssCompileCache[file], err = compileGCSS(gcssReader) if err != nil { log.Println(" >> GCSS Error: ", err) httpHandleErrorText(w, err) return true } httpServeCompiledGCSS(w, file) return true }