api

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2025 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Response = ApiResponses{

	Ok: func(w http.ResponseWriter, data ...any) {
		Send(w, 200, data)
	},

	Created: func(w http.ResponseWriter, data ...any) {
		Send(w, 201, data)
	},

	NoContent: func(w http.ResponseWriter, data ...any) {
		Send(w, 204, nil)
	},

	BadRequest: func(w http.ResponseWriter, data ...any) {
		Send(w, http.StatusBadRequest, data)
	},

	Unauthorized: func(w http.ResponseWriter, data ...any) {
		Send(w, http.StatusUnauthorized, data)
	},

	Forbidden: func(w http.ResponseWriter, data ...any) {
		Send(w, http.StatusForbidden, data)
	},

	NotFound: func(w http.ResponseWriter, data ...any) {
		Send(w, http.StatusNotFound, data)
	},

	TooManyRequests: func(w http.ResponseWriter, data ...any) {
		Send(w, http.StatusTooManyRequests, data)
	},

	ServerError: func(w http.ResponseWriter, data ...any) {
		Send(w, http.StatusInternalServerError, data)
	},

	Send: func(w http.ResponseWriter, status int, data ...any) {
		Send(w, status, data)
	},

	Gzip: func(w http.ResponseWriter, status int, data ...any) {
		zip(w, status, data...)
	},

	StreamBytes: func(w http.ResponseWriter, status int, bytes []byte, name string) {
		w.Header().Set("Content-Type", "application/octet-stream")
		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%v\"", name))
		w.WriteHeader(status)
		w.Write(bytes)
	},

	StreamFile: func(w http.ResponseWriter, status int, binPath string, name string) {

		f, err := os.Open(binPath)
		if err != nil {

			Send(w, http.StatusInternalServerError, nil)
			return
		}
		defer f.Close()

		w.Header().Set("Content-Type", "application/octet-stream")
		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%v\"", name))
		w.WriteHeader(status)

		size, err := io.Copy(w, f)
		if err != nil {
			log.Println("Streaming failed:", err)
		}

		log.Printf("Copied %v bytes", size)

		err = os.RemoveAll(filepath.Dir(binPath))
		if err != nil {
			log.Println("Failed to clean up temp dir:", err)
		}
	},
}

Functions

func DecodeJSON

func DecodeJSON[T any](r *http.Request) (T, error)

func Send

func Send(w http.ResponseWriter, status int, data any)

Types

type APIServer

type APIServer struct {
	Addr   string
	Server http.Server
	Router *http.ServeMux
}

Core server & routing types

func NewApiServer

func NewApiServer(addr string, routes []RouteHandler) *APIServer

addr = :PORT

func (*APIServer) ListenAndServe

func (s *APIServer) ListenAndServe() error

type ApiResponses

type ApiResponses struct {
	Ok              response
	Created         response
	NoContent       response
	ServerError     response
	NotFound        response
	Unauthorized    response
	Forbidden       response
	TooManyRequests response
	BadRequest      response
	Send            customResponse
	Gzip            func(w http.ResponseWriter, status int, data ...any)
	StreamBytes     func(w http.ResponseWriter, status int, bytes []byte, name string)
	StreamFile      func(w http.ResponseWriter, status int, binPath string, name string)
}

type HTTPMethods

type HTTPMethods struct {
	GET    string
	POST   string
	PUT    string
	PATCH  string
	DELETE string
}

HTTP method helper struct

type HandlerFn

type HandlerFn = func(http.ResponseWriter, *http.Request)

Handler and Middleware abstractions

func RecoveryMW

func RecoveryMW(next HandlerFn) HandlerFn

Place on the front of the mw pipe to handle all panics

type Middleware

type Middleware = func(HandlerFn) HandlerFn

func CORSMW

func CORSMW(origin string) Middleware

func HeaderAuthMW

func HeaderAuthMW(validator func(token string) bool, header string, requireBearer bool) Middleware

func LoggerMW

func LoggerMW(logger *log.Logger) Middleware

Initalize logger to dictate logging action

func StaticBearerAuthMW

func StaticBearerAuthMW(expectedKey string) Middleware

func TimeoutMW

func TimeoutMW(d time.Duration) Middleware

type PathBuilder

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

func NewPathBuilder

func NewPathBuilder(base string) PathBuilder

func (*PathBuilder) Append

func (pb *PathBuilder) Append(parts ...string) PathBuilder

func (*PathBuilder) Methods

func (pb *PathBuilder) Methods() HTTPMethods

type RouteHandler

type RouteHandler struct {
	MethodAndPath string
	Handler       HandlerFn
	Middleware    []Middleware
}

Jump to

Keyboard shortcuts

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