package page import ( "encoding/json" "net/http" "path/filepath" "gopkg.in/yaml.v3" ) // logReq just maks that we've done a request in the log, format is roughly: // remoteAddr, Method, statusCode, page path. func logReq(r *http.Request, statusCode int) { Logger.Printf("%s %s %d %s", r.RemoteAddr, r.Method, statusCode, GetPagePath(r)) } // logErr logs messages in the format of: // RemoteAddr, Method, path: pagePath, message, error. func logErr(r *http.Request, msg string, err error) { Logger.Printf("%s %s path: %s %s: %s", r.RemoteAddr, r.Method, GetPagePath(r), msg, err) } // plainResp sends a text/plain response down to the writer with the appropriate // status code and a body of msg. func plainResp(w http.ResponseWriter, statusCode int, msg string) { w.Header().Set("Content-type", "text/plain") w.WriteHeader(statusCode) _, _ = w.Write([]byte(msg)) } // GetURLPath returns r.URL.Path, unless it's merely a slash, then // it returns "index". Usefulf for defining your own handlers. func GetURLPath(r *http.Request) string { u := r.URL.Path if u == "/" { u = "/index" } return u } // GetPagePath is the same as GetURLPath except that it joins it with // the current directory ".". Also useful in defining your own handlers. func GetPagePath(r *http.Request) string { return filepath.Join(".", GetURLPath(r)) } // EncodeYaml is meant to be used in templating functions to encode // arbitrary information as a yaml string. func (p Page) EncodeYaml(data interface{}) string { if data == nil { data = p } b, err := yaml.Marshal(data) if err != nil { Logger.Println("Encountered error in EncodeYaml: ", err) } return string(b) } // EncodeJSON is meant to be used in templating functions to encode // arbitrary information as a JSON string. func (p Page) EncodeJSON(data interface{}) string { if data == nil { data = p } b, err := json.MarshalIndent(data, "", " ") if err != nil { Logger.Println("Encountered error in EncodeJson: ", err) } return string(b) } // EncodeJSON is meant to be used in templating functions to encode // arbitrary information as a JSON string. func (p Page) EncodeJSONCompact(data interface{}) string { if data == nil { data = p } b, err := json.Marshal(data) if err != nil { Logger.Println("Encountered error in EncodeJSONCompact: ", err) } return string(b) }