pf

package module
v0.1.1-preview Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2024 License: MIT Imports: 11 Imported by: 1

README

Pickme Framework

Go Reference

Эта кароч либа для моей команды на проде ну чтобы не на джаве ну кароч

ну типа пишешь ручки а она типа генерит сваггер и работает с ашипками ну кароч

package main

import (
	"github.com/TaeKwonZeus/pf"
	"net/http"
	"log"
)

func Ping(w pf.ResponseWriter[string], r *pf.Request[struct{}]) error {
	return w.OK("Pong!")
}

func main() {
	r := pf.NewRouter()
	pf.Get(r, "/ping", Ping)

	err := http.ListenAndServe(":8080", r)
	if err != nil {
		log.Fatal(err)
	}
}

Documentation

Overview

pf (Pickme Framework) is a REST API library based on chi for use by me and my boys on hackathons, olympiads and for personal projects.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBadRequest                   error = httpError(400)
	ErrUnauthorized                 error = httpError(401)
	ErrPaymentRequired              error = httpError(402)
	ErrForbidden                    error = httpError(403)
	ErrNotFound                     error = httpError(404)
	ErrMethodNotAllowed             error = httpError(405)
	ErrNotAcceptable                error = httpError(406)
	ErrProxyAuthRequired            error = httpError(407)
	ErrRequestTimeout               error = httpError(408)
	ErrConflict                     error = httpError(409)
	ErrGone                         error = httpError(410)
	ErrLengthRequired               error = httpError(411)
	ErrPreconditionFailed           error = httpError(412)
	ErrRequestEntityTooLarge        error = httpError(413)
	ErrRequestURITooLong            error = httpError(414)
	ErrUnsupportedMediaType         error = httpError(415)
	ErrRequestedRangeNotSatisfiable error = httpError(416)
	ErrExpectationFailed            error = httpError(417)
	ErrImATeapot                    error = httpError(418)
	ErrMisdirectedRequest           error = httpError(421)
	ErrUnprocessableEntity          error = httpError(422)
	ErrLocked                       error = httpError(423)
	ErrFailedDependency             error = httpError(424)
	ErrTooEarly                     error = httpError(425)
	ErrUpgradeRequired              error = httpError(426)
	ErrPreconditionRequired         error = httpError(428)
	ErrTooManyRequests              error = httpError(429)
	ErrRequestHeaderFieldsTooLarge  error = httpError(431)
	ErrUnavailableForLegalReasons   error = httpError(451)

	ErrInternalServerError           error = httpError(500)
	ErrNotImplemented                error = httpError(501)
	ErrBadGateway                    error = httpError(502)
	ErrServiceUnavailable            error = httpError(503)
	ErrGatewayTimeout                error = httpError(504)
	ErrHTTPVersionNotSupported       error = httpError(505)
	ErrVariantAlsoNegotiates         error = httpError(506)
	ErrInsufficientStorage           error = httpError(507)
	ErrLoopDetected                  error = httpError(508)
	ErrNotExtended                   error = httpError(510)
	ErrNetworkAuthenticationRequired error = httpError(511)
)

Functions

func Delete

func Delete[Req, Res any](r *Router, path string, handler Handler[Req, Res], props ...HandlerProperty)

func Get

func Get[Res any](r *Router, path string, handler Handler[struct{}, Res], props ...HandlerProperty)

func Handle

func Handle(r *Router, path string, handler http.Handler)

Handle routes handler to the path. You should not use this for regular function handlers, as they won't show up in Swagger.

func HandleError

func HandleError(w http.ResponseWriter, err error)

HandleError handles any errors that might occur in handlers and middlewares. For errors defined in the package, HandleError sets the appropriate status code and responds with the standard message. For other errors, HandleError logs the error with slog.Error and responds with status code 500 and the standard message.

func Head(r *Router, path string, handler Handler[struct{}, struct{}], props ...HandlerProperty)

func Method

func Method[Req, Res any](r *Router, method method, path string, handler Handler[Req, Res], props ...HandlerProperty)

Method adds routes for path that matches the HTTP method specified by method. Method also adds metadata, consisting of the request and response type, as well as props, for use by Swagger and the like.

func Mount

func Mount(r *Router, path string, subrouter *Router)

Mount mounts a sub-router along path.

func Options

func Options[Res any](r *Router, path string, handler Handler[struct{}, Res], props ...HandlerProperty)

func Patch

func Patch[Req, Res any](r *Router, path string, handler Handler[Req, Res], props ...HandlerProperty)

func Post

func Post[Req, Res any](r *Router, path string, handler Handler[Req, Res], props ...HandlerProperty)

func Put

func Put[Req, Res any](r *Router, path string, handler Handler[Req, Res], props ...HandlerProperty)

func Route

func Route(r *Router, path string, fn func(r *Router))

Route mounts a sub-router along path.

func Use

func Use(r *Router, middlewares ...func(next http.Handler) http.Handler)

Use appends one or more middlewares onto the Router stack.

Types

type Handler

type Handler[Req, Res any] func(w ResponseWriter[Res], r *Request[Req]) error

Handler represents an HTTP callback. Handler takes in a parsed Request (optionally, to do nothing set Req to struct{}), as well as a ResponseWriter that may marshal the response. Request and ResponseWriter contain the underlying http.Request and ResponseWriter from net/http.

type HandlerProperty

type HandlerProperty func(op *spec.Operation)

HandlerProperty represents a modification to the handler's metadata (summary, description etc.) for Swagger.

func WithConsumes

func WithConsumes(mime string) HandlerProperty

WithConsumes sets the MIME type the handler expects as the request body.

func WithDescription

func WithDescription(description string) HandlerProperty

WithSummary sets the handler's description.

func WithProduces

func WithProduces(mime string) HandlerProperty

WithProduces sets the MIME type the handler produces as a response.

func WithQuery

func WithQuery(query ...string) HandlerProperty

WithSummary adds query parameters to the handler's metadata.

func WithSummary

func WithSummary(summary string) HandlerProperty

WithSummary sets the handler's summary.

type Request

type Request[T any] struct {
	*http.Request
	Body T
}

Request wraps http.Request and provides a Body of type T. Body is parsed depending on T: If T is struct{}, then Body is equal to struct{}{}; If T is []byte, then the request body is read into Body; If T is *multipart.Form, then the form data is fetched using ParseMultipartForm. Otherwise, the response body is assumed to be JSON and deserialized into Body.

func (*Request[T]) URLParam

func (r *Request[T]) URLParam(key string) string

URLParam returns the url parameter specified by key.

type ResponseWriter

type ResponseWriter[T any] struct {
	http.ResponseWriter
}

ResponseWriter wraps an http.ResponseWriter instance, adding convenience methods for marshaling the output.

func (*ResponseWriter[T]) JSON

func (w *ResponseWriter[T]) JSON(status int, response T) error

JSON marshals response as JSON and sends an HTTP response with the status code specified by status.

func (*ResponseWriter[T]) OK

func (w *ResponseWriter[T]) OK(response T) error

OK marshals response as JSON and sends an HTTP response with status code 200.

type Router

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

Router is a composable router based on chi.Mux that tracks handler request and response body signatures.

func NewRouter

func NewRouter() *Router

NewRouter returns a newly initialized Router.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

type SwaggerInfo

type SwaggerInfo struct {
	Title          string
	Description    string
	TermsOfService string
	ContactName    string
	ContactURL     string
	ContactEmail   string
	License        string
	LicenseURL     string
	Version        string
}

SwaggerInfo represents metadata about the API.

Jump to

Keyboard shortcuts

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