simplehttp

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 14, 2024 License: MIT Imports: 12 Imported by: 0

README

simplehttp

A bare-bones HTTP/1.0 web framework for go.

Note: this package should not be used in a production environment. It was purely created as a learning opportunity to gain experience with go.

Documentation

Full documentation can be found on go's official documentation site at https://pkg.go.dev/github.com/BennettB123/simplehttp.

Features

✅ custom routing in the form of registering custom callbacks to be invoked when specific HTTP methods/paths are requested.
✅ handling multiple concurrent requests in parallel.
✅ methods to view information about incoming HTTP requests.
✅ convienent methods to modify HTTP responses.
✅ custom logger interface to receive messages about connections, incoming requests, and outgoing responses.

Basic Example

The following program will create a Server listening on port 8080. It will respond to incoming GET requests to the '/hello-world' path.

func main() {
	server := simplehttp.NewServer(8080)

	server.Get("/hello-world", func(req simplehttp.Request, res *simplehttp.Response) error {
		res.SetHtml("<h1>Hello, world!</h1>")
		return nil
	})

	err := server.Start()
	if err != nil {
		fmt.Println("There was an error starting the server:", err)
	}
}

See cmd/basicserver/basicserver.go for more examples.

Documentation

Overview

The simplehttp package is a bare-bones HTTP/1.0 web framework for go. It supports registering callbacks that are invoked whenever specific HTTP methods and URLs are requested by a client. It takes heavy inspiration from the Express web framework for Node.

Note: this package should not be used in a production environment. It was purely created as a learning opportunity to gain experience with go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CallbackFunc

type CallbackFunc = func(Request, *Response) error

CallbackFunc is the function signature that represents a callback to be registered on the Server. The Request parameter can be used to view properties on the incoming request. The *Response parameter can be used to modify the response that will be returned. If an error is returned in a callback, the server will automatically return a 500 Internal Server Error response.

type Logger

type Logger interface {
	// LogMessage accepts a string to be logged.
	LogMessage(string)
}

Logger is a simple interface to be given to the Server.

type Request

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

Request represents an HTTP request coming from a client. It provides several getter methods to view properties about the request, such as Request.Headers, Request.Body, and Request.Parameters. A Request should be seen as immutable.

func (Request) Body

func (r Request) Body() string

Returns the request's body.

func (Request) Headers

func (r Request) Headers() map[string]string

Returns the request's headers.

func (Request) Method

func (r Request) Method() string

Returns the request's HTTP method. For example, GET, POST, PUT, DELETE, etc.

func (Request) Parameters

func (r Request) Parameters() map[string][]string

Returns the request's parameters. For example, if the request's parameters are '?key1=value1&key1=value2&key2=value3', the result from Parameters would be map[key1:[value1 value2] key2:[value3]].

func (Request) Path

func (r Request) Path() string

Returns the escaped form of the path in the request's URI.

func (Request) RawMessage

func (r Request) RawMessage() string

Returns the exact HTTP request that was received by the client.

func (Request) RawParameters

func (r Request) RawParameters() string

Returns the request's parameters as a raw, unparsed string.

func (Request) String

func (r Request) String() string

Rebuilds a string that represents the entire HTTP request. The output from this method is not guaranteed to exactly match the request received by the Server (for example, headers may not be ordered the same). If the exact HTTP request is required, use Request.RawMessage instead.

func (Request) Uri

func (r Request) Uri() string

Returns the request's Request-URI.

type Response

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

Response represents an HTTP reponse to be returned to a client. It provides several getter methods to view its properties as well as several methods to edit the response before it is sent.

func (Response) Body

func (r Response) Body() string

Returns the response's body.

func (Response) Headers

func (r Response) Headers() map[string]string

Returns the response's headers.

func (Response) ReasonPhrase

func (r Response) ReasonPhrase() string

Returns the response's Reason-Phrase.

func (*Response) SetFile

func (r *Response) SetFile(path string) error

Sets the Response's body to the content in the file provided by the path parameter. The path can be either absolute or relative to the current working directory. The Content-Length header will be set appropriately. The Content-Type header will be determined by the file's extension using the mime.TypeByExtension function. Returns an error if the file could not be read, or if a Content-Type was unable to be determined.

func (*Response) SetFileWithContentType

func (r *Response) SetFileWithContentType(path string, contentType string) error

Sets the Response's body to the content in the file provided by the path parameter. The path can be either absolute or relative to the current working directory. Sets the Content-Type header to the value provided by the contentType parameter. The Content-Length header will be set appropriately. Returns an error if the file could not be read.

func (*Response) SetHeader

func (r *Response) SetHeader(key string, value string) error

Adds a single header to the Response. key is the header-field to be added, and value is the value of the new header. An error will be returned if the key contains a colon.

func (*Response) SetHtml

func (r *Response) SetHtml(html string)

Sets the Response's body to the provided html string. This method will also set the Content-Length header to the length of the provided input. The Content-Type header will be set to "text/html".

func (*Response) SetJson

func (r *Response) SetJson(obj any) error

Sets the Response's body to a JSON string. If obj is a string, the body will be set to the provided string. If obj is any other type, it will be marshalled to JSON using json.Marshal. This method will set the Content-Length header appropriately as well as setting the Content-Type header to "application/json". An error will be returned if there was an issue marshalling the obj.

func (*Response) SetStatus

func (r *Response) SetStatus(status uint)

Sets the Response's Status-Code to the value provided in the status parameter. A Reason-Phrase will also be set based on the status code. See RFC 1945 Section 9 for a complete list of Status-Codes and Reason-Phrases. If a Status-Code is provided that does not appear in this list, the provided code will be set, however the Reason-Phrase will be 'unknown'.

func (Response) StatusCode

func (r Response) StatusCode() uint

Returns the response's Status-Code.

func (Response) String

func (r Response) String() string

Builds a string that represents the entire HTTP response.

type Server

type Server struct {
	// The Port that the server listens on
	Port uint16
	// MaxRequestBytes is the maximum number of bytes an incoming request can
	// be before the server rejects it.
	MaxRequestBytes uint
	// ReadTimeoutSeconds is the time in seconds that the server waits for a
	// request before closing the connection.
	ReadTimeoutSeconds int
	// Logger is a user-implementation of the [Logger] interface that the
	// server will send messages about incoming requests and
	// outgoing responses. If a Logger is not provided, the server will
	// discard all log messages.
	Logger Logger
	// contains filtered or unexported fields
}

A Server represents an HTTP server that listens on a specific port. A Server should only be created using the NewServer method to ensure it is properly initialized. The server does not support persistent connections. After a request has been received and a response has been returned, the server will close the connection.

func NewServer

func NewServer(port uint16) Server

Creates and initializes a new Server object and assigns port to [Server.Port]

func (*Server) Delete

func (s *Server) Delete(path string, callback CallbackFunc) error

Registers a callback that will be invoked whenever a DELETE request is made to the provided path. The callback is a function that takes in a Request and *Response and returns an error. See CallbackFunc for details on this function

func (*Server) Get

func (s *Server) Get(path string, callback CallbackFunc) error

Registers a callback that will be invoked whenever a GET request is made to the provided path. The callback is a function that takes in a Request and *Response and returns an error. See CallbackFunc for details on this function

func (*Server) Post

func (s *Server) Post(path string, callback CallbackFunc) error

Registers a callback that will be invoked whenever a POST request is made to the provided path. The callback is a function that takes in a Request and *Response and returns an error. See CallbackFunc for details on this function

func (*Server) Put

func (s *Server) Put(path string, callback CallbackFunc) error

Registers a callback that will be invoked whenever a PUT request is made to the provided path. The callback is a function that takes in a Request and *Response and returns an error. See CallbackFunc for details on this function

func (*Server) Start

func (s *Server) Start() error

Starts the Server and begins listening for requests. Multiple requests can be handled in parallel with no hard limit. Returns an error if the Server was unable to open a TCP listener.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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