HTTPNav

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: May 25, 2025 License: MIT Imports: 9 Imported by: 0

README

HTTPNav

HTTPNav is a lightweight HTTP/1.1 Go package designed to simplify HTTP request and response handling. It provides custom encoders and decoders to streamline working with HTTP headers and payloads.

Note: Their is not HTTPS support.

Features

  • 🧰 Custom encoders and decoders for HTTP headers and bodies

  • 📦 Simplified HTTP request and response handling

  • 🔧 Easy integration into existing Go projects

  • 🧪 Only HTTP v1.1

Installation

To install HTTPNav, use go get:

go get github.com/udan-jayanith/HTTPNav

Then, import it into your Go code:

import HTTPNav "github.com/udan-jayanith/HTTPNav"

Usage

Server

server contains server data and logic.

GetServer
HTTPNav.GetServer()

GetServer() Function returns a new server.

HandelFunc

HandelFunc takes HTTPRequestMethod, requestTarget and a handler. If requests httpMethod and requestTarget matches the handler handler will execute.

Ex:

server.HandleFunc(httpNav.Get, "/", func(response *httpNav.HTTPResponse, request *httpNav.HTTPRequest) {
		response.Write([]byte("Hello world. /"))
        //Write send a response back to the client.
})
StartServer
StartServer(":8080")

StartServer start the server(starts listing to incoming requests).

HTTPRequest

Parses the HTTP request and store in it. Then pointer to the HTTPRequest is passed to matching HandleFunc()

GetBodyAsBytes

This return Body as a slice of bytes. If Content-Length header is not included in the header GetBodyAsBytes() returns ContentLengthHeaderNotFound.

bodyBty, err := request.GetBodyAsBytes()
GetBodyAsJson
var v map[string]any
err := request.GetBodyAsJson(&v)

GetBodyAsJson parses the JSON-encoded data and stores the result in the value pointed to by v. If Content-Type is not in the header GetBodyAsJson returns ContentTypeHeaderNotFound. Else if Content-Type != "application/json" GetBodyAsJson returns InvalidContentType. It uses GetBodyAsBytes in underlying layer.

To see other functionalities see HTTPNav Go Doc or simpley see source code.

Contributing

Contributions are welcome! Feel free to open issues or submit pull requests.

License

This project is licensed under the MIT License. See the LICENSE.md file for details.

Documentation

Overview

HTTPNav is a HTTP 1.1 go package.

Index

Constants

This section is empty.

Variables

View Source
var (
	ContentLengthHeaderNotFound error = errors.New("Expected Content-Length header but not found.")
	ContentLengthIsEmpty        error = errors.New("Content-Length header is empty.")
)
View Source
var (
	ContentTypeHeaderNotFound error = errors.New("Content-Type header not found.")
	InvalidContentType        error = errors.New("Invalid content-type value")
)

Functions

This section is empty.

Types

type HTTPCallbackHandleFunc

type HTTPCallbackHandleFunc func(*HTTPResponse, *HTTPRequest)

type HTTPRequest

type HTTPRequest struct {
	RequestLine RequestLine
	Header      map[string]string
	// contains filtered or unexported fields
}

func (*HTTPRequest) GetBodyAsBytes

func (ht *HTTPRequest) GetBodyAsBytes() ([]byte, error)

This return Body as a slice of bytes. If Content-Length header is not included in the header GetBodyAsBytes() returns ContentLengthHeaderNotFound.

func (*HTTPRequest) GetBodyAsJson

func (ht *HTTPRequest) GetBodyAsJson(v any) error

GetBodyAsJson parses the JSON-encoded data and stores the result in the value pointed to by v. If Content-Type is not in the header GetBodyAsJson returns ContentTypeHeaderNotFound. Else if Content-Type != "application/json" GetBodyAsJson returns InvalidContentType. It uses GetBodyAsBytes in underlying layer.

func (*HTTPRequest) GetBodyAsString

func (ht *HTTPRequest) GetBodyAsString() (string, error)

GetBodyAsString return body as string. It uses GetBodyAsBytes in underlying layer.

func (*HTTPRequest) GetHeader

func (ht *HTTPRequest) GetHeader(field string) (string, bool)

GetHeader returns header value for a give field.

func (*HTTPRequest) GetReader

func (ht *HTTPRequest) GetReader() *bufio.Reader

GetReader() return the reader after reading the header.

type HTTPRequestMethod

type HTTPRequestMethod string
var (
	/*The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should not contain a request content.*/
	Get HTTPRequestMethod = "GET"
	/*The HEAD method asks for a response identical to a GET request, but without a response body.*/
	Head HTTPRequestMethod = "HEAD"
	/*The POST method submits an entity to the specified resource, often causing a change in state or side effects on the server.*/
	Post HTTPRequestMethod = "POST"
	/*The PUT method replaces all current representations of the target resource with the request content.*/
	Put HTTPRequestMethod = "PUT"
	/*The DELETE method deletes the specified resource.*/
	Delete HTTPRequestMethod = "DELETE"
	/*The CONNECT method establishes a tunnel to the server identified by the target resource.*/
	Connect HTTPRequestMethod = "CONNECT"
	/*The OPTIONS method describes the communication options for the target resource.*/
	Options HTTPRequestMethod = "OPTIONS"
	/*The TRACE method performs a message loop-back test along the path to the target resource.*/
	Trace HTTPRequestMethod = "TRACE"
	/*The PATCH method applies partial modifications to a resource.*/
	Patch HTTPRequestMethod = "PATCH"
)

Http methods.

type HTTPResponse

type HTTPResponse struct {
	ResponseLine HTTPResponseLine
	// contains filtered or unexported fields
}

HTTPResponse is used when sending a response to a HTTP request.

func (*HTTPResponse) EncodeHTTPResponse

func (hr *HTTPResponse) EncodeHTTPResponse() []byte

EncodeHTTPResponse return HTTP response.

func (*HTTPResponse) SetHeaderLine

func (hr *HTTPResponse) SetHeaderLine(field, value string)

SetHeaderLine header add header linde to the HTTP header as field: value.

func (*HTTPResponse) Write

func (hr *HTTPResponse) Write(b []byte) (int, error)

Write writes to the HTTPResponse body.

func (*HTTPResponse) WriteAsJson

func (hr *HTTPResponse) WriteAsJson(v any) error

WriteAsJson set body as value pointed by v.

type HTTPResponseLine

type HTTPResponseLine struct {
	StatusCode        int
	StatusCodeMessage string
}

func (*HTTPResponseLine) EncodeRequestLine

func (hr *HTTPResponseLine) EncodeRequestLine() []byte

EncodeRequestLine return the current responses request line.

func (*HTTPResponseLine) SetStatusCode

func (hr *HTTPResponseLine) SetStatusCode(statusCode int)

SetStatusCode sets the HTTP status code.

type HandlerData

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

type RequestLine

type RequestLine struct {
	Method   HTTPRequestMethod
	Target   RequestTarget
	Protocol string
}

type RequestTarget

type RequestTarget struct {
	RequestTarget string
	Path          string
	QueryParams   map[string]string
}

func (*RequestTarget) GetQuery

func (target *RequestTarget) GetQuery(field string) (string, bool)

GetQuery returns RequestTarget query param value for given field.

type Server

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

func GetServer

func GetServer() *Server

GetServer returns a new Server

func (*Server) HandleFunc

func (s *Server) HandleFunc(method HTTPRequestMethod, requestTarget string, handler HTTPCallbackHandleFunc)

HandelFunc takes HTTPRequestMethod, requestTarget and a handler. If requests httpMethod and requestTarget matches the handler handler will execute.

func (*Server) StartServer

func (s *Server) StartServer(port string) error

StartServer start the server(start listing).

Jump to

Keyboard shortcuts

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