web

package module
v0.0.0-...-a0d03c3 Latest Latest
Warning

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

Go to latest
Published: Jan 23, 2023 License: MIT Imports: 23 Imported by: 8

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidPassword = NewError("invalid password")
View Source
var ErrInvalidRegistrationCode = NewError("invalid registration code")
View Source
var ErrInvalidSession = NewError("invalid session")
View Source
var ErrMethodNotSupported = NewError("method not supported")
View Source
var ErrUserNotFound = NewError("user not found")
View Source
var NoError = NewError("")

Functions

func HandleCORS

func HandleCORS(w http.ResponseWriter, r *http.Request)

func IsHTML

func IsHTML(r *http.Request) bool

func LogRequest

func LogRequest(r *http.Request, dir string) error

func NewID

func NewID() string

func PathParts

func PathParts(p string) []string

Deprecated.

func ServeAny

func ServeAny(v any, w http.ResponseWriter, r *http.Request)

func ServeBadRequest

func ServeBadRequest(w http.ResponseWriter, r *http.Request)

func ServeHTTPS

func ServeHTTPS(h http.Handler, acmeConfig ACMEConfig) error

func ServeInternalServerError

func ServeInternalServerError(w http.ResponseWriter, r *http.Request)

func ServeMethodNotAllowed

func ServeMethodNotAllowed(w http.ResponseWriter, r *http.Request)

func ServeNotFound

func ServeNotFound(w http.ResponseWriter, r *http.Request)

func ServeUnauthorized

func ServeUnauthorized(w http.ResponseWriter, r *http.Request)

Types

type ACMEConfig

type ACMEConfig struct {
	Hosts      []string
	AdminEmail string
	CertDir    string
}

func (*ACMEConfig) CertManager

func (c *ACMEConfig) CertManager() autocert.Manager

func (*ACMEConfig) HTTPSServer

func (c *ACMEConfig) HTTPSServer(mux http.Handler, certManager autocert.Manager) http.Server

type AddRequest

type AddRequest struct {
	ID string `json:"id"`
}

type Admin

type Admin struct {
	PhoneNumber string

	TwillioAccountSID  string
	TwillioAuthToken   string
	TwillioPhoneNumber string
}

Admin is a web administrator.

func (*Admin) Notify

func (a *Admin) Notify(message string) error

Notify sends a text message to the admin.

type AppConfig

type AppConfig struct {
	StaticFiles map[string][]byte
	RootType    Type
	Schema      struct {
		User   Schema
		Org    Schema
		Public Schema
	}
	Views map[string]*View
}

type AuthClient

type AuthClient struct {
	AuthServerAddr string
}

func (*AuthClient) CreateInviteCode

func (c *AuthClient) CreateInviteCode()

func (*AuthClient) Login

func (c *AuthClient) Login()

func (*AuthClient) Logout

func (c *AuthClient) Logout()

func (*AuthClient) Register

func (c *AuthClient) Register()

func (*AuthClient) ValidateSession

func (c *AuthClient) ValidateSession(s *Session) error

type AuthDB

type AuthDB struct {
	// Users are the users of the service.
	Users map[string]*User `json:"users"`
	// RegistrationCodes are needed to create new users.
	// Codes can be created by sending a POST request to /register with a valid registrar key.
	RegistrationCodes map[string]bool `json:"registration_codes"`
	// RegistrarKey is a secret key that is needed to generate registration codes.
	// If your service is open to new signups, you can share this string publicly.
	RegistrarKey string `json:"registrar_key"`
	// AdminID is the UserID of the admin.
	AdminID string `json:"admin_id"`
	// contains filtered or unexported fields
}

AuthDB is a service for authentication. It is intended to be set up as a service that is used by other services and not end users. It is intended to be used on the open internet.

func NewAuthDB

func NewAuthDB(adminPassword, registrarKey string) *AuthDB

func (*AuthDB) GetUserFromRequest

func (s *AuthDB) GetUserFromRequest(r *http.Request) string

GetUserFromRequest returns the user associated with the given request. If the user is not found, it returns nil.

func (*AuthDB) Invite

func (s *AuthDB) Invite() string

Invite creates a new registration code and returns it.

func (*AuthDB) Login

func (s *AuthDB) Login(userID, password string) (string, error)

Login returns a new session token for the given user ID and password. If it returns an error, it will be of type ErrInvalidPassword or ErrUserNotFound.

func (*AuthDB) Register

func (s *AuthDB) Register(registrationCode, password string) (string, error)

Register creates a new user with the given password and returns the new user's ID. If it returns an error, it will be of type ErrInvalidRegistrationCode.

func (*AuthDB) ServeHTTP

func (s *AuthDB) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves the authentication server. There are 5 endpoints: /invite, /register, /login, /logout, and /user.

func (*AuthDB) User

func (s *AuthDB) User(id string) (*User, bool)

User returns the User with the given ID.

type ChecksumServer

type ChecksumServer struct {
	Dir string
}

ChecksumServer is a server for checksums.

func (*ChecksumServer) ServeHTTP

func (s *ChecksumServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves HTTP requests.

type Collection

type Collection[T http.Handler] map[string]T

func (Collection[T]) Delete

func (c Collection[T]) Delete(id string)

func (Collection[T]) Get

func (c Collection[T]) Get(id string) (T, bool)

func (Collection[T]) Post

func (c Collection[T]) Post(v T) string

func (Collection[T]) Put

func (c Collection[T]) Put(id string, v T)

func (Collection[T]) ServeHTTP

func (c Collection[T]) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (Collection[T]) WriteHTML

func (c Collection[T]) WriteHTML(w io.Writer) error

type Command

type Command struct {
	Assignments []string `json:"assignments"`
	Func        string   `json:"func"`
	Args        []string `json:"args"`
}

type Comment

type Comment struct {
	Author  string
	Message string
}

type Counter

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

func (*Counter) Dec

func (c *Counter) Dec()

func (*Counter) Inc

func (c *Counter) Inc()

func (*Counter) Value

func (c *Counter) Value() int

type CreateResponse

type CreateResponse struct {
	ID    string `json:"id"`
	Error string `json:"error",omitempty,omitemptykey:""`
}

type DevServer

type DevServer struct {
	Apps map[string]http.Handler
}

func (*DevServer) ServeHTTP

func (d *DevServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Error

type Error struct {
	Err string `json:"error" omitemptykey:""`
}

func NewError

func NewError(msg string) Error

func (Error) Error

func (e Error) Error() string

type Event

type Event struct {
	Type    string `json:"type"`
	Payload []byte `json:"payload"`
}

type ExecRequest

type ExecRequest struct {
	Token  string         `json:"token"`
	Pkg    string         `json:"pkg"`
	Func   string         `json:"func"`
	Inputs map[string]any `json:"inputs"`
}

type Field

type Field struct {
	Type        Type         `json:"type"`
	EnglishName english.Name `json:"name"`
}

type File

type File struct {
	// Type is the type of the file.
	Type Type `json:"type"`
	// Owner is the ID of the organization that owns the file.
	Owner string `json:"owner"`
	// Owners is a map of user IDs that own the file.
	// Deprecated: Use Owner instead.
	Owners map[string]bool `json:"owners"`
	// Name is the name of the file.
	// Deprecated: Use EnglishName instead.
	Name string `json:"name"`
	// EnglishName is the English-language name of the file.
	EnglishName english.Name `json:"english_name"`
	// Doc is the documentation for the file.
	Doc string `json:"doc"`
	// Comments are a list of comments on the file.
	Comments []Comment `json:"comments"`
	// Public decides whether the file is publicly available or not.
	// This means it can be viewed by anyone.
	// It can still only be edited by members of the owner organization.
	Public bool `json:"public"`
	// CreatedAt is the Unix timestamp of when the file was created.
	CreatedAt int64 `json:"created_at"`
	// UpdatedAt is the Unix timestamp of when the file was last updated.
	UpdatedAt int64 `json:"updated_at"`
	// SHA256 is the SHA256 hash of the file.
	SHA256 string `json:"sha256"`
	// Size is the size of the file in bytes.
	Size int64 `json:"size"`
}

File is core concept in the web library. It is used throughout the package to represent files and directories. It doesn't actually contain the file's contents, but a SHA256 hash of the file's contents.

func (*File) ServeHTTP

func (f *File) ServeHTTP(w http.ResponseWriter, r *http.Request)

type FileServer

type FileServer struct {
	AuthServerAddr string
}

FileServer is a data structure that implements the http.Handler interface. It serves files and directories on the open web. Clients can GET and PUT files and directories.

func (*FileServer) ServeHTTP

func (s *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves HTTP requests for files. GET /path/to/file returns the file. PUT /path/to/file creates or updates the file. GET /path/to/dir returns the directory as a special type of file.

type Folder

type Folder struct {
	Contents []string
}

type Function

type Function struct {
	Name     string    `json:"name"`
	Inputs   []Field   `json:"inputs"`
	Outputs  []Field   `json:"outputs"`
	Validate []Command `json:"validate"`
	Execute  []Command `json:"execute"`
}

type HomePage

type HomePage struct {
	Title string
}

func (HomePage) File

func (h HomePage) File() File

func (HomePage) Type

func (h HomePage) Type() Type

type LoginRequeset

type LoginRequeset struct {
	UserID   string `json:"user_id"`
	Password string `json:"password"`
}

type Metadata

type Metadata struct {
	// Type is the type of the file.
	// It can be one of the following:
	// - any builtin Go type
	// - any type defined in the Go standard library
	// - any exported type defined in a public MIT licensed library on pkg.go.dev
	Type string `json:"type"`
	// Owner is the ID of the organization that owns the file.
	Owner string `json:"owner"`
	// Owners is a map of user IDs that own the file.
	// Deprecated: Use Owner instead.
	Owners map[string]bool `json:"owners"`
	// Name is the name of the file.
	// Deprecated: Use EnglishName instead.
	Name string `json:"name"`
	// EnglishName is the English-language name of the file.
	EnglishName english.Name `json:"english_name"`
	// Doc is the documentation for the file.
	Doc string `json:"doc"`
	// Comments are a list of comments on the file.
	Comments []Comment `json:"comments"`
	// Public decides whether the file is publicly available or not.
	// This means it can be viewed by anyone.
	// It can still only be edited by members of the owner organization.
	Public bool `json:"public"`
	// CreatedAt is the Unix timestamp of when the file was created.
	CreatedAt int64 `json:"created_at"`
	// UpdatedAt is the Unix timestamp of when the file was last updated.
	UpdatedAt int64 `json:"updated_at"`
	// SHA256 is the SHA256 hash of the file.
	SHA256 string `json:"sha256"`
	// Size is the size of the file in bytes.
	Size int64 `json:"size"`
}

Metadata is the metadata for a file.

type MetadataServer

type MetadataServer map[string]*Metadata

MetadataServer is a server for global metadata.

func (MetadataServer) Owner

func (s MetadataServer) Owner(path Path) string

Owner returns the owner of the given path.

func (MetadataServer) Owners

func (s MetadataServer) Owners(path Path) map[string]bool

Owners returns the owners of the given path. Deprecated.

func (MetadataServer) ServeHTTP

func (s MetadataServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves HTTP requests for metadata.

type Model

type Model struct {
	Name    string     `json:"name"`
	Fields  []Field    `json:"fields"`
	Methods []Function `json:"methods"`
}

type Org

type Org[DataType any] struct {
	Data DataType
}

func (*Org[T]) ServeHTTP

func (o *Org[T]) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Path

type Path []string

func ParsePath

func ParsePath(p string) Path

ParsePath parses a url.URL.Path into a web.Path.

func (Path) Append

func (p Path) Append(name string) Path

func (Path) First

func (p Path) First() string

func (Path) Last

func (p Path) Last() string

func (Path) Length

func (p Path) Length() int

func (Path) Parts

func (p Path) Parts() []string

Parts returns the parts of the path.

func (Path) Pop

func (p Path) Pop() Path

func (Path) Rest

func (p Path) Rest() Path

func (Path) Root

func (p Path) Root() bool

func (Path) Second

func (p Path) Second() string

func (Path) SecondLast

func (p Path) SecondLast() string

func (Path) String

func (p Path) String() string

String returns the path as a string.

type Platform

type Platform struct {
	LetsEncryptEmail string
	CertDir          string
	Apps             map[string]http.Handler
	CmdURL           string
}

func (*Platform) ServeHTTP

func (p *Platform) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Platform) Start

func (p *Platform) Start() error

type RemoveRequest

type RemoveRequest struct {
	ID string `json:"id"`
}

type Request

type Request struct {
	Timestamp int64               `json:"timestamp"`
	FromIP    string              `json:"from_ip"`
	Method    string              `json:"method"`
	Host      string              `json:"host"`
	Path      string              `json:"path"`
	Query     map[string][]string `json:"query"`
	Headers   map[string][]string `json:"headers"`
	Body      []byte              `json:"body"`
}

func BuildRequest

func BuildRequest(r *http.Request) (*Request, error)

Build request returns a newly created Request object. It leaves the request body open for further processing.

type RequestLog

type RequestLog struct {
	FromIP  string              `json:"from_ip"`
	Method  string              `json:"method"`
	Host    string              `json:"host"`
	Path    string              `json:"path"`
	Query   map[string][]string `json:"query"`
	Headers map[string][]string `json:"headers"`
	Body    []byte              `json:"body"`
}

type Resource

type Resource interface {
	Type() string
	WriteJSON(w io.Writer) error
	WriteHTML(w io.Writer) error
	CallMethod(method string, input io.Reader, output io.Writer) error
	ID() string
	Name() english.Name
	Doc() string
}

type SaaS

type SaaS[OrgDataType http.Handler] struct {
	Orgs map[string]Org[OrgDataType]
}

type Schema

type Schema struct {
	Fields []Field
}

func NewSchema

func NewSchema() *Schema

func (*Schema) AddField

func (s *Schema) AddField(name english.Name, t Type) error

func (*Schema) ChangeFieldName

func (s *Schema) ChangeFieldName(oldName, newName english.Name) error

func (*Schema) ChangeFieldType

func (s *Schema) ChangeFieldType(fieldName english.Name, newType Type) error

func (*Schema) MoveField

func (s *Schema) MoveField(fromIndex, toIndex int) error

func (*Schema) RemoveField

func (s *Schema) RemoveField(name english.Name) error

func (*Schema) ServeHTTP

func (s *Schema) ServeHTTP(w http.ResponseWriter, r *http.Request)

type SearchResults

type SearchResults struct{}

type Session

type Session struct {
	UserID string `json:"user_id"`
	Token  string `json:"token"`
}

type Type

type Type struct {
	// IsRef is true if the value is reference.
	IsRef bool `json:"is_ref"`
	// IsList is true if the value is a list.
	IsList bool `json:"is_list"`
	// BaseType can be one of the following:
	// - any builtin Go type
	// - any type defined in the Go standard library
	// - any exported type defined in a public MIT licensed library on pkg.go.dev
	// If the ID is not builtin, it must be a valid Go import path followed by a dot and the type name.
	// For example, "github.com/library-development/go-web.File" is a valid ID.
	BaseType string `json:"base_type"`
}

Type is the type of the file.

func ParseType

func ParseType(s string) Type

type User

type User struct {
	PasswordHash  string          `json:"password_hash"`
	SessionTokens map[string]bool `json:"session_tokens"`
	Emails        []string        `json:"emails"`
}

func NewUser

func NewUser(password string) *User

func (*User) PrimaryEmail

func (u *User) PrimaryEmail() string

PrimaryEmail returns the primary email address of the user. It panic if the user has no email addresses.

type View

type View struct{}

Jump to

Keyboard shortcuts

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