webutil

package module
v1.1.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 31, 2021 License: MIT Imports: 15 Imported by: 0

README

Web Utility for Golang websites.

Webutil is a simple, lightweight utility for Golang websites.

It loads, selects the right mime, and caches static (js, css, image,...), and html files. It also has a place-holder to apply security in order to withhold a file (i.e. a javascript file).

Features

MIME Types

MIME types are configured and the corrected response header is written by default.

HTTP Response Wrapper
WriteResponse

Compression headers are added with each response; just pass the data that is to be displayed on a page to the WriteResponse function:

WriteResponse(data []byte, w http.ResponseWriter, r *http.Request)
HTTPExec

HTTPExec is an http wrapper. You can set timeout, pass headers, and have an option of receiving a log of the call. It returns the entire response for further parsing.

HTTPExec(method HTTPMethod, urlx string, hd http.Header, data []byte, tMillisec uint, logRequest bool) (HTTPResult, error)
Serve Static Files

ServeStaticFile can be setup for processing supporting files like css, js, and image files.

func (h *HTTP) ServeStaticFile(w http.ResponseWriter, r *http.Request)

All needed is assigning the path to the http handler as the following example:

mWebutil := webutil.NewHTTP(mInstallPath, 5*time.Minute)
http.HandleFunc("/assets/", mWebutil.ServeStaticFile)
Process Page Directives

Insert page directives inside html pages.

func (h *HTTP) ProcessPageCommands(b []byte) ([]byte, error)

Use the LoadFile directive to insert content inside a block; easily reuse pieces of code inside pages without writing separate code. Usage Example:

<div style="border:none">
  {{.$LoadFile:/web/html/my-cool-grid.html}}
</div>
Comments

You can leave comments in any file (.html, .js, .go,..), knowing that they will not reach the client.

{{.COMMENTS <your comments go here> }}
Run the test app

Documentation

Overview

Package webutil implements some Web utility functions. It also implments a cache mechanism for any file that is to be served via http.

Index

Constants

View Source
const (
	PageCmdLoadFile = "$LoadFile"
)

Variables

This section is empty.

Functions

func ReadFile added in v1.1.6

func ReadFile(name string) ([]byte, error)

The following is the same as the Go ReadFile() func with the exception of closing the file before return.

../src/os/file.go ReadFile reads the named file and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

func WriteResponse added in v1.1.5

func WriteResponse(data []byte, w http.ResponseWriter, r *http.Request)

WriteResponse writes the response. if gzip in present in the header, it will compress the respone before writing.

Types

type HTTP

type HTTP struct {
	RootPhysicalPath string
	CacheDuration    time.Duration
	Webcache         *webcache.Cache
}

HTTP are common http callback functions.

func NewHTTP

func NewHTTP(rootPhysicalPath string, cacheDuration time.Duration) *HTTP

NewHTTP creates a new instance of webutil.

func (*HTTP) AddSuffix

func (h *HTTP) AddSuffix(rPath string, fileExtension string) string

AddSuffix adds file extension (i.e. .html) to the path if not present. It will check for /null in the path (maybe passed by javascript in error). It also adds index.html to the path, if the path is a directory.

func (*HTTP) GenerateSessionID

func (h *HTTP) GenerateSessionID(r *http.Request) string

GenerateSessionID creates a sessionID that is comprised of a double MD5 of caller's IP address and user agent.

func (*HTTP) GetCookie

func (h *HTTP) GetCookie(cname string, r *http.Request) string

GetCookie finds a target cookie and returns the string.

func (*HTTP) GetMIMEContentType

func (h *HTTP) GetMIMEContentType(ext string) string

GetMIMEContentType first checks the standard extensions i.e. .png, .js,... if not found it uses a custom parsing to return the right content type.

func (*HTTP) IsPortNoValid added in v1.1.2

func (h *HTTP) IsPortNoValid(portno int) bool

IsPortNoValid checks the ragne of an tcp/ip port number.

func (*HTTP) ProcessPageCommands added in v1.1.6

func (h *HTTP) ProcessPageCommands(b []byte) ([]byte, error)

ProcessPageCommands replaces command directive blocks with their results. In the following example the content of the file /web/html/index.html will be placed inside the div tag

<div style="border:none">
  {{.$LoadFile:/web/html/index.html}}
</div>

func (*HTTP) RemoveCommentsFromBiteArry added in v1.1.2

func (h *HTTP) RemoveCommentsFromBiteArry(b []byte, begin string, end string) []byte

RemoveCommentsFromByBiteArry removes a block of text from a byte array.

func (*HTTP) RemoveCommentsFromByBiteArry

func (h *HTTP) RemoveCommentsFromByBiteArry(b []byte, begin string, end string) []byte

RemoveCommentsFromByBiteArry removes a block of text from a byte array.

func (*HTTP) RemoveCommentsFromString added in v1.1.1

func (h *HTTP) RemoveCommentsFromString(s string, begin string, end string) string

RemoveCommentsFromString removes a block of text from inside an string.

func (*HTTP) RemoveCookie

func (h *HTTP) RemoveCookie(cname string, r *http.Request, w http.ResponseWriter) bool

RemoveCookie a cookie by setting its expiration in the past.

func (*HTTP) ServeStaticFile

func (h *HTTP) ServeStaticFile(w http.ResponseWriter, r *http.Request)

ServeStaticFile processes static files for a website. Static files are the ones that require no additional rending before their content is written to a ResponseWrite object, hence no custom error handling, if file is not found. The MIME is written to the Response Header according to the extension of the requested file. Examples are: .js, .css, .html.

func (*HTTP) SetContentTypeAndWrite added in v1.1.1

func (h *HTTP) SetContentTypeAndWrite(w http.ResponseWriter, r *http.Request, f []byte) bool

SetContentTypeAndWrite writes the response and reutrns false, if mime type not found; returns true if mime type found. It uses the conent passed via an arg rather than than that of the request.

func (*HTTP) SetCookie

func (h *HTTP) SetCookie(cname string, cvalue string, maxAge int, w http.ResponseWriter) string

SetCookie creates a cookie by setting the Set-Cookie header. A value of zeor for maxAge will mean that the cookie will never expire.

type HTTPMethod added in v1.1.5

type HTTPMethod int
const (
	GET HTTPMethod = iota
	HEAD
	POST
	PUT
	CONNECT
	DELETE
	OPTIONS
	PATCH
	TRACE
)

func (HTTPMethod) String added in v1.1.5

func (i HTTPMethod) String() string

type HTTPResult added in v1.1.5

type HTTPResult struct {
	ResponseData []byte
	RequestDump  string
	Response     *http.Response
	Request      *http.Request
}

func HTTPExec added in v1.1.5

func HTTPExec(method HTTPMethod, urlx string, hd http.Header, data []byte, tMillisec uint, logRequest bool) (HTTPResult, error)

HTTPExec send http request to a server. It returns data, response, and error (if any). Although the entire reponse, and request are returned, the data is also read into a []byte for a quick lookup by the caller.

type UserSession

type UserSession struct {
	Email                        string
	CustomerID                   int
	FirstName                    string
	LastName                     string
	EmailVerified                bool
	SessionID                    string
	VerificationCodeExpires      time.Time
	LastVerificationCodeRequest  time.Time
	VerificationCodeRequestCount int
}

UserSession defines a web user session.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL