nexus

package module
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 13 Imported by: 0

README

nexus

Nexus is a Go library designed to simplify the creation of HTTP servers by leveraging Go's standard library. It provides developers with a streamlined interface to set up robust and efficient web servers without relying on external frameworks. By utilizing Go's native capabilities, Nexus ensures optimal performance and seamless integration within the Go ecosystem.

Install

go get github.com/codecraftkit/nexus
Stand Alone
package main

import (
	"github.com/codecraftkit/flash-server/internal/config"
	"github.com/codecraftkit/nexus"
	"net/http"
	"os"
)

func main() {
	config.LoadEnv()

	server := &nexus.Server{
		//Secret:      os.Getenv("SECRET"),
		Port:        os.Getenv("PORT"),
		Debug:       true,
		//SecretMiddleware: func(next http.Handler, server *nexus.Server) http.Handler, // replace the default secret middleware
		Middlewares: []func(next http.Handler, server *nexus.Server) http.Handler{
			//VerifySession,
		},
		Endpoints: [][]nexus.Endpoint{
			HomeEndpoints,
			UserEndpoints,
		},
	}

	server.Run()

}

func Home(w http.ResponseWriter, r *http.Request) {

	w.Write([]byte("Home"))

}

func Users(w http.ResponseWriter, r *http.Request) {

	users := []struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}{
		{Name: "John", Age: 30},
		{Name: "Mary", Age: 25},
		{Name: "Peter", Age: 40},
	}

	nexus.ResponseWithJSON(w, http.StatusOK, users)

}

func UsersSave(w http.ResponseWriter, r *http.Request) {

	// save user

	// ...
	nexus.ResponseWithJSON(w, http.StatusOK, map[string]string{"message": "User saved"})

}

var HomeEndpoints = []nexus.Endpoint{
	{Path: "GET /home", HandlerFunc: Home},
}

var UserEndpoints = []nexus.Endpoint{
	{Path: "GET /users", HandlerFunc: Users},
	{Path: "POST /users", HandlerFunc: UsersSave},
}

func VerifySession(next http.Handler) http.Handler {

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		session := r.Header.Get("x-session")
		if session == "" {
			w.WriteHeader(http.StatusForbidden)
			return
		}
		next.ServeHTTP(w, r)
	})

}
Multiple Servers
package main

import (
	"github.com/codecraftkit/flash-server/internal/config"
	"github.com/codecraftkit/nexus"
	"net/http"
	"os"
)

func main() {
	config.LoadEnv()

	server1 := &nexus.Server{
		//Secret: os.Getenv("SECRET"),
		Port:        "8081", //os.Getenv("PORT"),
		Debug:       true,
		//SecretMiddleware: func(next http.Handler, server *nexus.Server) http.Handler, // replace the default secret middleware
		Middlewares: []func(next http.Handler, server *nexus.Server) http.Handler{
			//VerifySession,
		},
		Endpoints: [][]nexus.Endpoint{
			HomeEndpoints,
			UserEndpoints,
		},
	}

	server2 := &nexus.Server{
		Port:  "8082",
		Debug: true,
		Endpoints: [][]nexus.Endpoint{
			[]nexus.Endpoint{
				{
					Path: "GET /",
					HandlerFunc: func(w http.ResponseWriter, r *http.Request) {
						w.Write([]byte("Server 2"))
					},
				},
			},
		},
	}

	nexus.Serve([]*nexus.Server{server1, server2})

}

func Home(w http.ResponseWriter, r *http.Request) {

	w.Write([]byte("Home"))

}

func Users(w http.ResponseWriter, r *http.Request) {

	users := []struct {
		Name string `json:"name"`
		Age  int    `json:"age"`
	}{
		{Name: "John", Age: 30},
		{Name: "Mary", Age: 25},
		{Name: "Peter", Age: 40},
	}

	nexus.ResponseWithJSON(w, http.StatusOK, users)

}

func UsersSave(w http.ResponseWriter, r *http.Request) {

	// save user

	// ...
	nexus.ResponseWithJSON(w, http.StatusOK, map[string]string{"message": "User saved"})

}

var HomeEndpoints = []nexus.Endpoint{
	{Path: "GET /home", HandlerFunc: Home},
}

var UserEndpoints = []nexus.Endpoint{
	{Path: "GET /users", HandlerFunc: Users},
	{Path: "POST /users", HandlerFunc: UsersSave},
}

func VerifySession(next http.Handler, server *nexus.Server) http.Handler {

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		session := r.Header.Get("x-session")
		if session == "" {
			w.WriteHeader(http.StatusForbidden)
			return
		}
		next.ServeHTTP(w, r)
	})

}


Documentation

Index

Constants

This section is empty.

Variables

View Source
var ServerEndpoints = []Endpoint{
	{Path: "GET /_health", HandlerServerFunc: Health, Options: EndpointOptions{IsPublic: true, NoRequiresAuthentication: true, IgnorePrefix: true}},
	{Path: "GET /_routes", HandlerServerFunc: RoutesList, Options: EndpointOptions{IsPublic: true, NoRequiresAuthentication: true, IgnorePrefix: true}},
	{Path: "GET /_routes/raw", HandlerServerFunc: RawRoutesList, Options: EndpointOptions{IsPublic: true, NoRequiresAuthentication: true, IgnorePrefix: true}},
}

ServerEndpoints is the list of endpoints for the server

Functions

func GetOptions added in v1.3.2

func GetOptions(opt url.Values) (skip, limit, page int64)

func Health

func Health(server *Server) http.HandlerFunc

Health check if the server is running

func RawRoutesList added in v1.3.0

func RawRoutesList(server *Server) http.HandlerFunc

func RequestScheme added in v1.3.3

func RequestScheme(r *http.Request) string

func ResponseJsonWithError added in v1.3.2

func ResponseJsonWithError(w http.ResponseWriter, code int, errorResponse *ErrorResponse) error

func ResponseWithError

func ResponseWithError(w http.ResponseWriter, code int, msg string) error

ResponseWithError return a json response with an error

func ResponseWithJSON

func ResponseWithJSON(w http.ResponseWriter, code int, payload interface{}) error

ResponseWithJSON return a json response

func ResponseWithPagination added in v1.3.0

func ResponseWithPagination(w http.ResponseWriter, code int, payload interface{}) error

func ResponseWithPaginationTest added in v1.3.2

func ResponseWithPaginationTest(w http.ResponseWriter, code int, options *PaginationOptions) error

func RoutesList

func RoutesList(server *Server) http.HandlerFunc

RoutesList return all routes

func Serve added in v1.1.0

func Serve(servers []*Server)

Serve set and run several Severs

Types

type Endpoint added in v1.2.0

type Endpoint struct {
	Path              string
	HandlerFunc       http.HandlerFunc
	Handler           http.Handler                          // Handler is a http.Handler and is used to create a new http.Handler with the server's middlewares and endpoints
	HandlerServerFunc func(server *Server) http.HandlerFunc // HandlerServerFunc is a function that returns a http.HandlerFunc and is used to create a new http.HandlerFunc with the server's middlewares and endpoints
	Options           EndpointOptions
	RegexPattern      *regexp.Regexp
}

Endpoint is a struct that contains the endpoint's configuration and handlers

type EndpointOptions added in v1.2.0

type EndpointOptions struct {
	IsPublic                 bool
	NoRequiresAuthentication bool
	IgnorePrefix             bool
}

EndpointOptions is a struct that contains the endpoint's options

type ErrorResponse added in v1.3.2

type ErrorResponse struct {
	Code     int               `json:"code"`
	Message  string            `json:"message"`
	CodeName string            `json:"code_name"`
	Errors   map[string]string `json:"errors"`
}

type GroupOptions added in v1.3.14

type GroupOptions struct {
	Middlewares []func(next http.Handler) http.Handler
}

type PaginationOptions added in v1.3.2

type PaginationOptions struct {
	Page    int64
	Limit   int64
	Skip    int64
	Payload interface{}
	Path    string
	Total   int64
}

type ResponsePagination added in v1.3.0

type ResponsePagination struct {
	TotalPages   int64       `json:"total_pages"`
	Total        int64       `json:"total"`
	CurrentPage  int64       `json:"current_page"`
	From         int64       `json:"from"`
	To           int64       `json:"to"`
	Offset       int64       `json:"offset"`
	Limit        int64       `json:"limit"`
	PerPage      int         `json:"per_page"`
	Path         string      `json:"path"`
	FirstPageURL string      `json:"first_page_url"`
	NextPageURL  string      `json:"next_page_url"`
	LastPageURL  string      `json:"last_page_url"`
	PrevPageURL  string      `json:"prev_page_url"`
	Data         interface{} `json:"data"`
}

func (*ResponsePagination) Set added in v1.3.2

func (p *ResponsePagination) Set()

type Server

type Server struct {
	ServerName           string
	ServerNumber         string
	RunningServerMessage string
	Secret               string
	Debug                bool
	Port                 string
	Middlewares          []func(next http.Handler, server *Server) http.Handler
	Endpoints            [][]Endpoint
	EndpointsPaths       map[string]*Endpoint
	CorsOptions          cors.Options
	Settings             *Settings
}

Server is a struct that contains the server's configuration and endpoints

func (*Server) ApplyMiddlewares added in v1.2.0

func (server *Server) ApplyMiddlewares(mux http.Handler) http.Handler

ApplyMiddlewares apply all middlewares to the mux; if the server is in debug mode, the server will be register the LogRequest middleware that will log the request on the console if the server has a secret, the server will be register the ValidateSecret middleware that will check if the request has a secret

func (*Server) Endpoint added in v1.3.3

func (server *Server) Endpoint(path string, handler http.HandlerFunc)

func (*Server) EndpointIsPublic added in v1.2.0

func (server *Server) EndpointIsPublic(r *http.Request) bool

EndpointIsPublic evalue if the endpoint is public

func (*Server) GetEndpoint added in v1.2.0

func (server *Server) GetEndpoint(r *http.Request) (*Endpoint, bool)

GetEndpoint evaluate if a path exists in the endpoints and return the endpoint and a bool if exists

func (*Server) GetEndpoints added in v1.2.0

func (server *Server) GetEndpoints() map[string]*Endpoint

GetEndpoints return all endpoints

func (*Server) Group added in v1.3.3

func (server *Server) Group(group string, apiEndpoints []Endpoint)

func (*Server) GroupWithOptions added in v1.3.14

func (server *Server) GroupWithOptions(group string, apiEndpoints []Endpoint, groupOptions *GroupOptions)

func (*Server) LogRequest added in v1.2.0

func (server *Server) LogRequest(next http.Handler) http.Handler

LogRequest log the request on the console

func (*Server) NoRequiresAuthentication added in v1.3.13

func (server *Server) NoRequiresAuthentication(r *http.Request) bool

func (*Server) Run added in v1.2.1

func (server *Server) Run()

Run a new Server

func (*Server) Use added in v1.3.3

func (server *Server) Use(middlewares ...func(next http.Handler, server *Server) http.Handler)

func (*Server) ValidateSecret added in v1.2.0

func (server *Server) ValidateSecret(next http.Handler) http.Handler

ValidateSecret check if the request has a secret

type Settings added in v1.3.3

type Settings struct {
	IgnoreSecret bool
	PathPrefix   string
}

Jump to

Keyboard shortcuts

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