httpserver

package module
v1.1.5 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2021 License: MIT Imports: 36 Imported by: 0

README

httpserver

Documentation

Index

Constants

View Source
const (
	MinCompressSize = 2048
)

Variables

View Source
var Accepted = newHerr(http.StatusAccepted, "Accpeted")
View Source
var BadGateway = newHerr(http.StatusBadGateway, "Bad Gateway")
View Source
var BadRequest = newHerr(http.StatusBadRequest, "Bad Request")
View Source
var Conflict = newHerr(http.StatusConflict, "Conflict")
View Source
var Created = newHerr(http.StatusCreated, "Created")
View Source
var Forbidden = newHerr(http.StatusForbidden, "Forbidden")
View Source
var Found = newRedirect(http.StatusFound, "Found")
View Source
var GatewayTimeout = newHerr(http.StatusGatewayTimeout, "Gateway Timeout")
View Source
var Gone = newHerr(http.StatusGone, "Gone")
View Source
var InternalServerError = newHerr(http.StatusInternalServerError, "Internal Server Error")
View Source
var MethodNotAllowed = newMethodNotAllowed()
View Source
var MovedPermanently = newRedirect(http.StatusMovedPermanently, "Moved Permanently")
View Source
var NoContent = newHerr(http.StatusNoContent, "No Content")
View Source
var NotAcceptable = newHerr(http.StatusNotAcceptable, "Not Acceptable")
View Source
var NotFound = newNotFound()
View Source
var NotImplemented = newHerr(http.StatusNotImplemented, "Not Implemented")
View Source
var NotModified = newHerr(http.StatusNotModified, "Not Modified")
View Source
var OK = newHerr(http.StatusOK, "OK")
View Source
var PartialContent = newHerr(http.StatusPartialContent, "Partial Content")
View Source
var PermanentRedirect = newRedirect(http.StatusPermanentRedirect, "Permanent Redirect")
View Source
var PreconditionFailed = newHerr(http.StatusPreconditionFailed, "Precondition Failed")
View Source
var RequestTimeout = newHerr(http.StatusRequestTimeout, "Request Timeout")
View Source
var ServiceUnavailable = newHerr(http.StatusServiceUnavailable, "Service Unavailable")
View Source
var TemporaryRedirect = newRedirect(http.StatusTemporaryRedirect, "Temporary Redirect")
View Source
var TooManyRequests = newHerr(http.StatusTooManyRequests, "Too Many Requests")
View Source
var Unauthorized = newHerr(http.StatusUnauthorized, "Login Required")

Functions

func CheckIfMatch

func CheckIfMatch(r *http.Request, etag string) *bool

func CheckIfModifiedSince

func CheckIfModifiedSince(r *http.Request, modTime time.Time) *bool

func CheckIfNoneMatch

func CheckIfNoneMatch(r *http.Request, etag string) *bool

func CheckIfRange

func CheckIfRange(r *http.Request, modTime time.Time, etag string) *bool

func CheckIfUnmodifiedSince

func CheckIfUnmodifiedSince(r *http.Request, modTime time.Time) *bool

func CheckPreconditions

func CheckPreconditions(r *http.Request, modTime time.Time, etag string) error

func CompressMiddleware

func CompressMiddleware(handler http.Handler) http.Handler

func ContextRequestId

func ContextRequestId(ctx context.Context) string

func ContextRequestVars

func ContextRequestVars(ctx context.Context) map[string]string

func CopyToFile

func CopyToFile(src io.Reader, fn string, overwrite bool) (string, error)

func CreateRequestContext

func CreateRequestContext(srv *Server, req *http.Request) *http.Request

func EnsureDir

func EnsureDir(fn string) error

func EnvEval

func EnvEval(s string) string

func ExternalURL

func ExternalURL(r *http.Request) *url.URL

func Forwarded

func Forwarded(r *http.Request) []map[string]string

func GenEtag

func GenEtag(f io.Reader) string

func ParseIPNet

func ParseIPNet(netstr string) *net.IPNet

func Proxy

func Proxy(w http.ResponseWriter, req *http.Request, proxyUrl string)

func QueryScan

func QueryScan(req *http.Request, obj interface{}) error

func ReadJSON

func ReadJSON(req *http.Request, target interface{}) error

func ScanETag

func ScanETag(s string) (etag string, remain string)

func SendJSON

func SendJSON(w http.ResponseWriter, obj interface{})

func ServeWS

func ServeWS(hub Hub, w http.ResponseWriter, req *http.Request) (interface{}, error)

func SetDefaultContentType

func SetDefaultContentType(w http.ResponseWriter, ct string)

func ValidateRouter

func ValidateRouter(r Router) error

Types

type APIError added in v1.1.0

type APIError interface {
	Error() string
	StatusCode() int
	SetStatus(int) APIError
	SetMessage(string) APIError
	AddContent(string, interface{}) APIError
	Unwrap() error
	MarshalJSON() ([]byte, error)
}

func NewAPIError added in v1.1.0

func NewAPIError(cause error, status int) APIError

type AccountMatcher

type AccountMatcher interface {
	GetUserByEmail(string) (*auth.User, error)
}

type AuthCfg

type AuthCfg interface {
	GetAuthKey() []byte
	GetTTL() time.Duration
	Authenticate(http.ResponseWriter, *http.Request) (string, error)
	Authorize(req *http.Request, username string) bool
}

type AuthConfig

type AuthConfig struct {
	PasswordFile string                        `json:"htpasswd" arg:"--htpasswd"`
	AuthKey      string                        `json:"key"      arg:"key"`
	TTL          int                           `json:"ttl"      arg:"ttl"`
	SocialLogin  map[string]*SocialLoginConfig `json:"social"`
	// contains filtered or unexported fields
}

func (*AuthConfig) GetAuthKey

func (cfg *AuthConfig) GetAuthKey() []byte

func (*AuthConfig) GetTTL

func (cfg *AuthConfig) GetTTL() time.Duration

func (*AuthConfig) Init

func (cfg *AuthConfig) Init(serverRoot string) error

func (*AuthConfig) ReadCookie

func (cfg *AuthConfig) ReadCookie(req *http.Request) *auth.User

func (*AuthConfig) ReadHeader added in v1.1.5

func (cfg *AuthConfig) ReadHeader(req *http.Request, name string) *auth.User

func (*AuthConfig) SetCookie

func (cfg *AuthConfig) SetCookie(w http.ResponseWriter, user *auth.User)

type BindConfig

type BindConfig struct {
	ExternalHostname string    `json:"hostname" arg:"hostname"`
	Port             int       `json:"port"     arg:"port"`
	SSL              SSLConfig `json:"ssl"      arg:"ssl"`
}

func (BindConfig) Host

func (cfg BindConfig) Host(netcfg NetCfg, ssl bool) string

func (*BindConfig) Init

func (cfg *BindConfig) Init(serverRoot string) error

func (BindConfig) Proto

func (cfg BindConfig) Proto(ssl bool) string

func (BindConfig) RootURL

func (cfg BindConfig) RootURL(netcfg NetCfg, ssl bool) *url.URL

type Client

type Client struct {
	Send chan []byte
	// contains filtered or unexported fields
}

func (*Client) Close

func (c *Client) Close()

func (*Client) NextWriter

func (c *Client) NextWriter(messageType int) (io.WriteCloser, error)

func (*Client) Open

func (c *Client) Open(conn *websocket.Conn) error

func (*Client) ReadMessage

func (c *Client) ReadMessage() (int, []byte, error)

func (*Client) ReadPump

func (c *Client) ReadPump()

func (*Client) SetPongHandler

func (c *Client) SetPongHandler(f func(string) error)

func (*Client) SetReadDeadline

func (c *Client) SetReadDeadline(t time.Time) error

func (*Client) SetReadLimit

func (c *Client) SetReadLimit(size int64)

func (*Client) SetWriteDeadline

func (c *Client) SetWriteDeadline(t time.Time) error

func (*Client) WriteMessage

func (c *Client) WriteMessage(messageType int, data []byte) error

func (*Client) WritePump

func (c *Client) WritePump()

type CompressResponseWriter

type CompressResponseWriter struct {
	// contains filtered or unexported fields
}

func NewCompressResponseWriter

func NewCompressResponseWriter(w http.ResponseWriter, r *http.Request) *CompressResponseWriter

func (*CompressResponseWriter) Close

func (w *CompressResponseWriter) Close() error

func (*CompressResponseWriter) Flush

func (w *CompressResponseWriter) Flush() error

func (*CompressResponseWriter) Header

func (w *CompressResponseWriter) Header() http.Header

func (*CompressResponseWriter) Hijack

func (*CompressResponseWriter) Write

func (w *CompressResponseWriter) Write(data []byte) (int, error)

func (*CompressResponseWriter) WriteHeader

func (w *CompressResponseWriter) WriteHeader(statusCode int)

type Datable

type Datable interface {
	LastModified() time.Time
}

type ETaggable

type ETaggable interface {
	ETag() string
}

type GenericHub

type GenericHub struct {
	Events chan interface{}
	// contains filtered or unexported fields
}

func NewGenericHub

func NewGenericHub(source chan interface{}) *GenericHub

func (*GenericHub) Broadcast

func (h *GenericHub) Broadcast(msg []byte)

func (*GenericHub) BroadcastEvent

func (h *GenericHub) BroadcastEvent(evt interface{})

func (*GenericHub) Closed

func (h *GenericHub) Closed() bool

func (*GenericHub) Register

func (h *GenericHub) Register(c *Client)

func (*GenericHub) Run

func (h *GenericHub) Run()

func (*GenericHub) Stop

func (h *GenericHub) Stop()

func (*GenericHub) Unregister

func (h *GenericHub) Unregister(c *Client)

type HTTPError

type HTTPError interface {
	error
	Cause() error
	Status() string
	StatusCode() int
	Headers() http.Header
	Message() string
	Wrap(error, string) HTTPError
	Wrapf(error, string, ...interface{}) HTTPError
	Unwrap() error
}

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, req *http.Request) (interface{}, error)

func (HandlerFunc) ServeHTTP

func (h HandlerFunc) ServeHTTP(w http.ResponseWriter, req *http.Request)

type Hub

type Hub interface {
	Run()
	Stop()
	Closed() bool
	Register(*Client)
	Unregister(*Client)
	Broadcast([]byte)
	BroadcastEvent(interface{})
}

type LogConfig

type LogConfig struct {
	Directory    string           `json:"directory"     arg:"dir"`
	AccessLog    string           `json:"access"        arg:"access"`
	ErrorLog     string           `json:"error"         arg:"error"`
	RotatePeriod int              `json:"rotate_period" arg:"rotate-period"`
	MaxSize      int64            `json:"max_size"      arg:"max-size"`
	RetainCount  int              `json:"retain"        arg:"retain"`
	LogLevel     logging.LogLevel `json:"level"         arg:"level"`
	// contains filtered or unexported fields
}

func (*LogConfig) AccessLogger

func (cfg *LogConfig) AccessLogger() (*logrotate.RotateFile, error)

func (*LogConfig) ErrorLogger

func (cfg *LogConfig) ErrorLogger() (*logging.Logger, error)

func (*LogConfig) Init

func (cfg *LogConfig) Init(serverRoot string) error

type Middleware

type Middleware func(http.Handler) http.Handler

type NetCfg

type NetCfg interface {
	GetNetwork() *net.IPNet
	GetInterface() *net.Interface
	GetIP() net.IP
}

type NetworkConfig

type NetworkConfig struct {
	Network   string `json:"network"   arg:"network"`
	Interface string `json:"interface" arg:"interface"`
	IP        string `json:"ip"        arg:"ip"`
	// contains filtered or unexported fields
}

func (*NetworkConfig) GetIP

func (cfg *NetworkConfig) GetIP() net.IP

func (*NetworkConfig) GetInterface

func (cfg *NetworkConfig) GetInterface() *net.Interface

func (*NetworkConfig) GetNetwork

func (cfg *NetworkConfig) GetNetwork() *net.IPNet

func (*NetworkConfig) Init

func (cfg *NetworkConfig) Init() error

type ProxyURL

type ProxyURL string

type Redirect

type Redirect string

type ResponseLogger

type ResponseLogger struct {
	// contains filtered or unexported fields
}

func NewResponseLogger

func NewResponseLogger(w http.ResponseWriter, r *http.Request) *ResponseLogger

func (*ResponseLogger) Header

func (rl *ResponseLogger) Header() http.Header

func (*ResponseLogger) Hijack

func (rl *ResponseLogger) Hijack() (net.Conn, *bufio.ReadWriter, error)

func (*ResponseLogger) Write

func (rl *ResponseLogger) Write(data []byte) (int, error)

func (*ResponseLogger) WriteHeader

func (rl *ResponseLogger) WriteHeader(statusCode int)

func (*ResponseLogger) WriteLog

func (rl *ResponseLogger) WriteLog(w io.Writer)

type Route

type Route struct {
	Method string
	Path   string
}

func (*Route) String

func (r *Route) String() string

func (*Route) URL

func (r *Route) URL(params map[string]string) string

type Router

type Router interface {
	Use(mw Middleware)
	Prefix(path string) Router
	LookupPath(method, path string) (http.Handler, map[string]string)
	Lookup(method string, path []string) (http.Handler, map[string]string)
	Handle(method, path string, handler http.Handler) error
	GET(path string, handler http.Handler) error
	POST(path string, handler http.Handler) error
	PUT(path string, handler http.Handler) error
	PATCH(path string, handler http.Handler) error
	DELETE(path string, handler http.Handler) error
	OPTIONS(path string, handler http.Handler) error
	Routes() []*Route
	Compile(parentMiddlewares []Middleware)
}

func NewRouter

func NewRouter() Router

type SSLConfig

type SSLConfig struct {
	Port     int    `json:"port"     arg:"port"`
	CertFile string `json:"cert"     arg:"cert"`
	KeyFile  string `json:"key"      arg:"key"`
	Disabled bool   `json:"disabled" arg:"disable"`
}

func (*SSLConfig) CheckCert

func (cfg *SSLConfig) CheckCert(serverRoot string) error

func (*SSLConfig) CheckKey

func (cfg *SSLConfig) CheckKey(serverRoot string) error

func (SSLConfig) Enabled

func (cfg SSLConfig) Enabled() bool

func (*SSLConfig) Init

func (cfg *SSLConfig) Init(serverRoot string) error

type Server

type Server struct {
	// contains filtered or unexported fields
}

func NewServer

func NewServer(cfg *ServerConfig) (*Server, error)

func (*Server) AccessLoggerMiddleware

func (srv *Server) AccessLoggerMiddleware() Middleware

func (*Server) ContextMiddleware

func (srv *Server) ContextMiddleware() Middleware

func (*Server) DELETE

func (srv *Server) DELETE(path string, handler http.Handler)

func (*Server) GET

func (srv *Server) GET(path string, handler http.Handler)

func (*Server) Handle

func (srv *Server) Handle(method, path string, handler http.Handler)

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe() error

func (*Server) OPTIONS

func (srv *Server) OPTIONS(path string, handler http.Handler)

func (*Server) PATCH

func (srv *Server) PATCH(path string, handler http.Handler)

func (*Server) POST

func (srv *Server) POST(path string, handler http.Handler)

func (*Server) PUT

func (srv *Server) PUT(path string, handler http.Handler)

func (*Server) Prefix

func (srv *Server) Prefix(path string) Router

func (*Server) ServeHTTP

func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) SetDefaultHandler

func (srv *Server) SetDefaultHandler(h http.Handler)

func (*Server) SetDefaultProxy

func (srv *Server) SetDefaultProxy(u string) error

func (*Server) SocialLogin

func (srv *Server) SocialLogin(prefix string, matcher AccountMatcher)

func (*Server) Use

func (srv *Server) Use(mw Middleware)

type ServerConfig

type ServerConfig struct {
	ConfigFile     string     `json:"-"               arg:"--config"` //,-c"`
	ServerRoot     string     `json:"server_root"     arg:"--server-root"`
	DocumentRoot   string     `json:"document_root"   arg:"--docroot"`
	DefaultProxy   string     `json:"default_proxy"   arg:"--proxy"`
	CacheDirectory string     `json:"cache_directory" arg:"--cache-dir"`
	PidFile        string     `json:"pidfile"         arg:"--pidfile"`
	Bind           BindConfig `json:"bind"            arg:"--bind"`
	Logging        LogConfig  `json:"log"             arg:"--log"`
	Auth           AuthConfig `json:"auth"            arg:"--auth"`
}

func Configure

func Configure() (*ServerConfig, error)

func DefaultServerConfig

func DefaultServerConfig() *ServerConfig

func (*ServerConfig) Abs

func (cfg *ServerConfig) Abs(fn string) (string, error)

func (*ServerConfig) CheckPidfile

func (cfg *ServerConfig) CheckPidfile() error

func (*ServerConfig) CheckPorts

func (cfg *ServerConfig) CheckPorts() error

func (*ServerConfig) Init

func (cfg *ServerConfig) Init() error

func (*ServerConfig) LoadFromFile

func (cfg *ServerConfig) LoadFromFile(fn string) error

func (*ServerConfig) ReadableFile

func (cfg *ServerConfig) ReadableFile(fn string) error

func (*ServerConfig) WritableDir

func (cfg *ServerConfig) WritableDir(dn string) error

type SocialLoginConfig

type SocialLoginConfig struct {
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
}

type StaticFile

type StaticFile string

type WebSocket

type WebSocket interface {
	Open(*websocket.Conn) error
	ReadPump()
	WritePump()
	Close()
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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