webutil

package
v0.0.0-...-c11726a Latest Latest
Warning

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

Go to latest
Published: May 3, 2024 License: Apache-2.0 Imports: 18 Imported by: 1

Documentation

Overview

Package webutils provides utility functions.

Index

Constants

View Source
const MsgTemplateError = "The server is unable to display this page."

Variables

View Source
var (
	ErrCSVNotSlice          = errors.New("data is not a slice")
	ErrCSVNotSliceOfStructs = errors.New("slice elements are not structs")
	ErrCSVWriteFailed       = errors.New("failed to write")
)
View Source
var (
	ErrEmailInvalidFrom       = errors.New("invalid from address")
	ErrEmailInvalidTo         = errors.New("invalid to address")
	ErrEmailInvalidSMTPConfig = errors.New("invalid SMTP configuration")
	ErrEmailSendFailed        = errors.New("failed to send email")
)

Functions

func CheckAllowedMethods

func CheckAllowedMethods(w http.ResponseWriter, r *http.Request, allowed ...string) bool

CheckAllowedMethods validates the request's method against a list of allowed methods. It automatically supports the OPTIONS method. If the method is allowed, it returns true. If the method is not allowed, it sets the 'Allow' header, responds appropriately, and returns false. The caller is advised to halt further processing if false is returned.

func ClientIP

func ClientIP(r *http.Request) string

ClientIP retrieves the client's IP address from the request. It prioritizes the X-Real-IP header value if present; otherwise, it falls back to the request's RemoteAddr.

func IsMethodOrError

func IsMethodOrError(w http.ResponseWriter, r *http.Request, method string) bool

IsMethodOrError verifies if the HTTP request method matches the specified method. It returns true if they match. Otherwise, it sends a 405 Method Not Allowed response and returns false. The caller should stop further processing if false is returned.

func Join

func Join(values []string, sep string) template.HTML

func MockSMTPServerConnection

func MockSMTPServerConnection(conn net.Conn)

MockSMTPServerConnection handles a single mock SMTP server connection.

func MockSMTPServerStart

func MockSMTPServerStart(ready chan<- bool, addr string)

MockSMTPServerStart starts a mock SMTP server using the provided addr. The server will signal on ready when setup is complete.

func RenderTemplateForTest

func RenderTemplateForTest(t *testing.T, tmpl *template.Template, name string, data any) string

RenderTemplateForTest renders a specific template with the provided data and returns the result as a string. This function is intended for use in tests to verify template output.

func RenderTemplateOrError

func RenderTemplateOrError(t *template.Template, w http.ResponseWriter, name string, data interface{}) error

RenderTemplateOrError executes the named template with the given data and writes the result to the provided HTTP response writer.

If an error occurs, sets HTTP response status to 500 and returns the error.

The caller must ensure no further writes are done for a non-nil error.

func RespondWithError

func RespondWithError(w http.ResponseWriter, code int)

RespondWithError sends an HTTP response with the specified error code and a corresponding error message.

func ServeFileHandler

func ServeFileHandler(filePath string) http.HandlerFunc

ServeFileHandler creates an HTTP handler function that serves a specified file. It verifies the file's existence and accessibility before creating the handler. Returns nil if the file does not exist or is not accessible.

func SetContentType

func SetContentType(w http.ResponseWriter, contentType string)

SetContentType sets headers for client to interpret response as contentType.

func SetContentTypeHTML

func SetContentTypeHTML(w http.ResponseWriter)

SetContentTypeHTML sets headers for client to interpret response as HTML.

func SetContentTypeText

func SetContentTypeText(w http.ResponseWriter)

SetContentTypeText sets headers for client to interpret response as plain text.

func SetNoCacheHeaders

func SetNoCacheHeaders(w http.ResponseWriter)

SetNoCacheHeaders sets headers for client to not cache the response content.

func SliceOfStructsToCSV

func SliceOfStructsToCSV(w io.Writer, data interface{}) error

SliceOfStructsToCSV writes a slice of structs to a CSV writer. It uses the struct field names as headers and their values as rows.

func TemplateNames

func TemplateNames(t *template.Template) []string

TemplateNames returns the names of all templates for t.

func Templates

func Templates(pattern string) (*template.Template, error)

Templates parses the templates matching pattern.

func TemplatesWithFuncs

func TemplatesWithFuncs(pattern string, funcMap template.FuncMap) (*template.Template, error)

TemplatesWithFuncs parses the templates with FuncMap.

func ToTimeZone

func ToTimeZone(t time.Time, name string) time.Time

Types

type RedactedSMTPConfig

type RedactedSMTPConfig SMTPConfig

RedactedSMTPConfig is copy of SMTPConfig that doesn't expose sensitve fields.

type SMTPConfig

type SMTPConfig struct {
	Host     string `required:"true"` // Host address.
	Port     string `required:"true"` // Port number.
	User     string `required:"true"` // Server username.
	Password string `required:"true"` // Server password.
}

SMTPConfig holds SMTP server settings for email functionality.

func (SMTPConfig) MarshalJSON

func (s SMTPConfig) MarshalJSON() ([]byte, error)

MarshalJSON customizes JSON marshalling to redact sensitive data.

func (SMTPConfig) SendMessage

func (s SMTPConfig) SendMessage(from string, to []string, subject, body string) error

SendMessage sends an email using the values provided.

func (SMTPConfig) String

func (s SMTPConfig) String() string

String returns a string representation of s with sensitive data redacted.

func (SMTPConfig) Valid

func (s SMTPConfig) Valid() bool

Valid checks s and returns true if required fields are non-empty.

Jump to

Keyboard shortcuts

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