server

package
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2024 License: MIT Imports: 17 Imported by: 3

README

Rest Server

The server package provides a simple and efficient way to expose server side RESTful APIs in Go. This package is built on top of the oss.nandlabs.io/golly/turbo package and provides a simple way to define routes and handle requests and maintain the configuration & lifecycle of the server.



Features

  • HTTP methods: GET, POST, PUT, DELETE
  • Query parameters
  • Request headers
  • TLS Configuration
  • Transport Layer Configuration
    • Connection Timeout
    • Read Timeout

Installation

To install the REST server, use the following command:

go get oss.nandlabs.io/golly/rest/server

Usage

To use the REST client in your Go project, you first need to import the package:

import "oss.nandlabs.io/golly/rest/server"
HTTP Methods : Sevve a GET Request
package main

import (
	"net/http"

	"oss.nandlabs.io/golly/lifecycle"
	"oss.nandlabs.io/golly/rest/server"
)

func main() {
	// Create a new server
	// Checkout  New(opts *Options) for customisng the server properties
	srv, err := server.Default()
	if err != nil {
		panic(err)
	}
	// this is the path prefix for each endpoint. Default is empty and no path prefix is added
	srv.Opts().PathPrefix = "/api/v1"
	// Add a GET endpoint
	srv.Get("healthCheck", func(ctx server.Context) {
		// Set the status code. Remember to set the status code before writing the response
		ctx.SetStatusCode(http.StatusOK)
		ctx.WriteString("Health Check Get")
	})
	// Add a POST endpoint
	srv.Post("healthCheck", func(ctx server.Context) {
		input, _ := ctx.GetBody()
		// Set the status code. Remember to set the status code before writing the response
		ctx.SetStatusCode(http.StatusOK)
		// Write the response
		ctx.WriteFrom(input)
	})
	// get the component manager
	mgr := lifecycle.NewSimpleComponentManager()
	// Register the server with the component manager
	mgr.Register(srv)
	// Start the server
	mgr.StartAndWait()
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidCertPath = errors.New("empty cert path")
View Source
var ErrInvalidConfig = errors.New("empty config path")
View Source
var ErrInvalidID = errors.New("empty id")
View Source
var ErrInvalidListenHost = errors.New("empty listen host")
View Source
var ErrInvalidListenPort = errors.New("empty listen port")
View Source
var ErrInvalidParamType = errors.New("invalid param type provided")
View Source
var ErrInvalidPrivateKeyPath = errors.New("empty private key path")
View Source
var ErrNilOptions = errors.New("nil options")

Functions

This section is empty.

Types

type Context

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

Context is the struct that holds the request and response of the server.

func (*Context) GetBody

func (c *Context) GetBody() (io.Reader, error)

GetBody returns the body of the request.

func (*Context) GetHeader

func (c *Context) GetHeader(name string) string

GetHeader returns the header of the request.

func (*Context) GetMethod

func (c *Context) GetMethod() string

GetMethod returns the method of the request.

func (*Context) GetParam

func (c *Context) GetParam(name string, typ Paramtype) (string, error)

Options is the struct that holds the configuration for the Server.

func (*Context) GetRequest

func (c *Context) GetRequest() *http.Request

GetRequest returns the request. for most Rest Use cases this would not be required

func (*Context) GetURL

func (c *Context) GetURL() string

GetURL returns the URL of the request.

func (*Context) HttpResWriter

func (c *Context) HttpResWriter() http.ResponseWriter

HttpResWriter returns the http.ResponseWriter

func (*Context) InHeaders

func (c *Context) InHeaders() http.Header

InHeaders returns the headers of the request.

func (*Context) Read

func (c *Context) Read(obj interface{}) error

Read reads the body of the request into the given object.

func (*Context) SetContentType

func (c *Context) SetContentType(contentType string)

SetContentType sets the content type of the response.

func (*Context) SetCookie

func (c *Context) SetCookie(cookie *http.Cookie)

SetCookie sets the cookie of the response.

func (*Context) SetHeader

func (c *Context) SetHeader(name, value string)

SetHeader sets the header of the response.

func (*Context) SetStatusCode

func (c *Context) SetStatusCode(statusCode int)

SetStatusCode sets the status code of the response.

func (*Context) Write

func (c *Context) Write(data interface{}, contentType string) error

Write writes the object to the response with the given content type and status code.

func (*Context) WriteData

func (c *Context) WriteData(data []byte) (int, error)

WriteData writes the data to the response.

func (*Context) WriteFrom

func (c *Context) WriteFrom(data io.Reader)

WriteFrom writes the data from the reader to the response.

func (*Context) WriteString

func (c *Context) WriteString(data string)

WriteString writes the string to the response.

type DataTypProvider

type DataTypProvider func() any

type HandlerFunc

type HandlerFunc func(context Context)

type Options

type Options struct {
	Id             string `json:"id" yaml:"id" bson:"id" mapstructure:"id"`
	PathPrefix     string `json:"path_prefix,omitempty" yaml:"path_prefix,omitempty" bson:"path_prefix,omitempty" mapstructure:"path_prefix,omitempty"`
	ListenHost     string `json:"listen_host" yaml:"listen_host" bson:"listen_host" mapstructure:"listen_host"`
	ListenPort     int16  `json:"listen_port" yaml:"listen_port" bson:"listen_port" mapstructure:"listen_port"`
	ReadTimeout    int64  `` /* 127-byte string literal not displayed */
	WriteTimeout   int64  `` /* 131-byte string literal not displayed */
	EnableTLS      bool   `json:"enable_tls" yaml:"enable_tls" bson:"enable_tls" mapstructure:"enable_tls"`
	PrivateKeyPath string `` /* 138-byte string literal not displayed */
	CertPath       string `json:"cert_path,omitempty" yaml:"cert_path,omitempty" bson:"cert_path,omitempty" mapstructure:"cert,omitempty"`
}

Options is the configuration for the server

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns the default options for the server

func NewOptions

func NewOptions() Options

NewOptions returns a new server options

func NewOptionsWithDefaults

func NewOptionsWithDefaults() Options

NewOptionsWithDefaults returns a new server options with default values

func (Options) GetCertPath

func (o Options) GetCertPath() string

GetCertPath returns the cert path

func (Options) GetEnableTLS

func (o Options) GetEnableTLS() bool

GetEnableTLS returns the enable TLS value

func (Options) GetListenHost

func (o Options) GetListenHost() string

GetListenHost returns the listen host

func (Options) GetListenPort

func (o Options) GetListenPort() int16

GetListenPort returns the listen port

func (Options) GetPrivateKeyPath

func (o Options) GetPrivateKeyPath() string

GetPrivateKeyPath returns the private key path

func (Options) SetCertPath

func (o Options) SetCertPath(certPath string) Options

SetCertPath sets the cert path

func (Options) SetEnableTLS

func (o Options) SetEnableTLS(enableTLS bool) Options

SetEnableTLS sets the enable TLS value

func (Options) SetListenHost

func (o Options) SetListenHost(host string) Options

SetListenHost sets the listen host

func (Options) SetListenPort

func (o Options) SetListenPort(port int16) Options

SetListenPort sets the listen port

func (Options) SetPrivateKeyPath

func (o Options) SetPrivateKeyPath(privateKeyPath string) Options

SetPrivateKeyPath sets the private key path

func (Options) Validate

func (o Options) Validate() error

Validate validates the server options

type Paramtype

type Paramtype int
const (
	QueryParam Paramtype = iota
	PathParam
)

type Server

type Server interface {
	// Server is a lifecytcle component
	lifecycle.Component
	// Opts returns the options of the server
	Opts() *Options
	// AddRoute adds a route to the server
	AddRoute(path string, handler HandlerFunc, method ...string) (err error)
	// AddRoute adds a route to the server
	Post(path string, handler HandlerFunc) (err error)
	// AddRoute adds a route to the server
	Get(path string, handler HandlerFunc) (err error)
	// AddRoute adds a route to the server
	Put(path string, handler HandlerFunc) (err error)
	// AddRoute adds a route to the server
	Delete(path string, handler HandlerFunc) (err error)
	// Unhandled adds a handler for unhandled routes
	Unhandled(handler HandlerFunc) (err error)
	// Unsupported adds a handler for unsupported methods
	Unsupported(handler HandlerFunc) (err error)
}

Server is the interface that wraps the ServeHTTP method.

func Default

func Default() (Server, error)

Default creates a new Server with the default options.

func New

func New(opts *Options) (rServer Server, err error)

New creates a new Server with the given options.

func NewFrom

func NewFrom(configPath string) (Server, error)

New creates a new Server with the given configuration file of the options.

Jump to

Keyboard shortcuts

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