poteto

package module
v0.27.0 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2025 License: MIT Imports: 16 Imported by: 0

README

Poteto

Simple Web Framework of GoLang

We have confirmed that it works with various versions: go@1.21.x, go@1.22.x, go@1.23.x

go get github.com/poteto-go/poteto@v0.26.5
go mod tidy

Example App For Poteto

https://github.com/poteto-go/poteto-sample-api/tree/main

or /examples

Poteto-Cli

It will be moved to other repo.

We support cli tool. But if you doesn't like it, you can create poteto-app w/o cli of course.

go install github.com/poteto-go/poteto/cmd/poteto-cli@v0.26.5

Create file.

poteto-cli new

fast mode.

poteto-cli new --fast
run app with hot-reload
  • create poteto.yaml
version: "0.27"
build_script_path: "main.go"
debug_mode: true
  • command
poteto-cli run
Demo

https://github.com/user-attachments/assets/4b739964-1b4f-4913-b643-5984bf1ceae1

Feature

JSONRPCAdapter (>=0.26.0)

KeyNote: You can serve JSONRPC server easily.

type (
  Calculator struct{}
  AdditionArgs   struct {
    Add, Added int
  }
)

func (tc *TestCalculator) Add(r *http.Request, args *AdditionArgs) int {
 return args.Add + args.Added
}

func main() {
  p := New()

  rpc := TestCalculator{}
  // you can access "/add/Calculator.Add"
  p.POST("/add", func(ctx Context) error {
    return PotetoJsonRPCAdapter[Calculator, AdditionArgs](ctx, &rpc)
  })

  p.Run("8080")
}
Leaf router & middlewareTree (>=0.21.0)
func main() {
	p := poteto.New()

	// Leaf >= 0.21.0
	p.Leaf("/users", func(userApi poteto.Leaf) {
		userApi.Register(middleware.CamaraWithConfig(middleware.DefaultCamaraConfig))
		userApi.GET("/", controller.UserHandler)
		userApi.GET("/:name", controller.UserIdHandler)
	})

	p.Run("127.0.0.1:8000")
}
Get RequestId Easily
func handler(ctx poteto.Context) error {
	requestId := ctx.RequestId()
}

How to use

package main

import (
	"net/http"

	"github.com/poteto-go/poteto"
	"github.com/poteto-go/poteto/middleware"
)

func main() {
	p := poteto.New()

	// CORS
	p.Register(middleware.CORSWithConfig(
		middleware.CORSConfig{
			AllowOrigins: []string{"*"},
			AllowMethods: []string{http.MethodGet, http.MethodPut, http.MethodPost, http.MethodDelete},
		},
	))

	// Leaf >= 0.21.0
	p.Leaf("/users", func(userApi poteto.Leaf) {
		userApi.Register(middleware.CamaraWithConfig(middleware.DefaultCamaraConfig))
		userApi.GET("/", controller.UserHandler)
		userApi.GET("/:name", controller.UserNameHandler)
	})

	p.Run("127.0.0.1:8000")
}

type User struct {
	Name any `json:"name"`
}

func UserHandler(ctx poteto.Context) error {
	user := User{
		Name: "user",
	}
	return ctx.JSON(http.StatusOK, user)
}

func UserNameHandler(ctx poteto.Context) error {
	name, _ := ctx.PathParam("name")
	user := User{
		Name: name,
	}
	return ctx.JSON(http.StatusOK, user)
}

Documentation

Index

Constants

View Source

Written By https://lazesoftware.com/ja/tool/brailleaagen/

Variables

View Source
var DefaultPotetoOption = PotetoOption{
	WithRequestId:   true,
	ListenerNetwork: "tcp",
}

Functions

func NewHttpError

func NewHttpError(code int, messages ...any) *httpError

func PotetoJsonRPCAdapter

func PotetoJsonRPCAdapter[T any, S any](ctx Context, api *T) error

inspired by https://github.com/kanocz/goginjsonrpc/blob/master/jsonrpc.go * Only Support "POST" method

Types

type Binder

type Binder interface {
	Bind(ctx Context, object any) error
}

func NewBinder

func NewBinder() Binder

type Context

type Context interface {
	JSON(code int, value any) error
	JSONRPCError(code int, message string, data string, id int) error
	Bind(object any) error
	WriteHeader(code int)
	JsonSerialize(value any) error
	JsonDeserialize(object any) error

	SetQueryParam(queryParams url.Values)
	SetParam(paramType string, paramUnit ParamUnit)
	PathParam(key string) (string, bool)
	QueryParam(key string) (string, bool)
	DebugParam() (string, bool)
	SetPath(path string)
	GetPath() string
	Set(key string, val any)
	Get(key string) (any, bool)

	GetResponse() *response
	SetResponseHeader(key, value string)
	GetRequest() *http.Request
	GetRequestHeaderParam(key string) string
	ExtractRequestHeaderParam(key string) []string

	NoContent() error

	// set request id to store
	// and return value
	RequestId() string

	GetRemoteIP() (string, error)
	RegisterTrustIPRange(ranges *net.IPNet)
	GetIPFromXFFHeader() (string, error)
	RealIP() (string, error)
	Reset(w http.ResponseWriter, r *http.Request)
	SetLogger(logger any)
	Logger() any
}

func NewContext

func NewContext(w http.ResponseWriter, r *http.Request) Context

type HandlerFunc

type HandlerFunc func(ctx Context) error

type HttpError

type HttpError interface {
	Error() string
	SetInternalError(err error)
	Unwrap() error
}

type HttpErrorHandler

type HttpErrorHandler interface {
	HandleHttpError(err error, ctx Context)
}

type HttpParam

type HttpParam interface {
	GetParam(paramType, key string) (string, bool)
	AddParam(paramType string, paramUnit ParamUnit)
	JsonSerialize() ([]byte, error)
}

func NewHttpParam

func NewHttpParam() HttpParam

type IPHandler

type IPHandler interface {
	SetIsTrustPrivateIP(flag bool)
	RegisterTrustIPRange(ranges *net.IPNet)
	CanTrust(ip net.IP) bool
	GetIPFromXFFHeader(ctx Context) (string, error)
	GetRemoteIP(ctx Context) (string, error)
	RealIP(ctx Context) (string, error)
}

type Leaf

type Leaf interface {
	Register(middlewares ...MiddlewareFunc) *middlewareTree
	GET(addPath string, handler HandlerFunc) error
	POST(addPath string, handler HandlerFunc) error
	PUT(addPath string, handler HandlerFunc) error
	PATCH(path string, handler HandlerFunc) error
	DELETE(addPath string, handler HandlerFunc) error
	HEAD(path string, handler HandlerFunc) error
	OPTIONS(path string, handler HandlerFunc) error
	TRACE(path string, handler HandlerFunc) error
	CONNECT(path string, handler HandlerFunc) error
}

func NewLeaf

func NewLeaf(poteto Poteto, basePath string) Leaf

type LeafHandler

type LeafHandler func(leaf Leaf)

type MiddlewareFunc

type MiddlewareFunc func(next HandlerFunc) HandlerFunc

type MiddlewareTree

type MiddlewareTree interface {
	SearchMiddlewares(pattern string) []MiddlewareFunc
	Insert(pattern string, middlewares ...MiddlewareFunc) *middlewareTree
	Register(middlewares ...MiddlewareFunc)
}

func NewMiddlewareTree

func NewMiddlewareTree() MiddlewareTree

type ParamUnit

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

type Poteto

type Poteto interface {
	// If requested, call this
	ServeHTTP(w http.ResponseWriter, r *http.Request)
	Run(addr string) error
	RunTLS(addr string, cert, key []byte) error
	Stop(ctx stdContext.Context) error

	Register(middlewares ...MiddlewareFunc)
	Combine(pattern string, middlewares ...MiddlewareFunc) *middlewareTree
	SetLogger(logger any)
	Leaf(basePath string, handler LeafHandler)

	GET(path string, handler HandlerFunc) error
	POST(path string, handler HandlerFunc) error
	PUT(path string, handler HandlerFunc) error
	PATCH(path string, handler HandlerFunc) error
	DELETE(path string, handler HandlerFunc) error
	HEAD(path string, handler HandlerFunc) error
	OPTIONS(path string, handler HandlerFunc) error
	TRACE(path string, handler HandlerFunc) error
	CONNECT(path string, handler HandlerFunc) error
	// contains filtered or unexported methods
}

func New

func New() Poteto

func NewWithOption

func NewWithOption(option PotetoOption) Poteto

type PotetoOption

type PotetoOption struct {
	WithRequestId   bool   `yaml:"with_request_id"`
	ListenerNetwork string `yaml:"listener_network"`
}

type Response

type Response interface {
	WriteHeader(code int)
	Write(b []byte) (int, error)

	SetStatus(code int)
	Header() http.Header
	SetHeader(key, value string)
	AddHeader(key, value string)
}

func NewResponse

func NewResponse(w http.ResponseWriter) Response

type Route

type Route interface {
	Search(path string) (*route, []ParamUnit)
	Insert(path string, handler HandlerFunc)

	GetHandler() HandlerFunc
}

func NewRoute

func NewRoute() Route

type Router

type Router interface {
	GET(path string, handler HandlerFunc) error
	POST(path string, handler HandlerFunc) error
	PUT(path string, handler HandlerFunc) error
	PATCH(path string, handler HandlerFunc) error
	DELETE(path string, handler HandlerFunc) error
	HEAD(path string, handler HandlerFunc) error
	OPTIONS(path string, handler HandlerFunc) error
	TRACE(path string, handler HandlerFunc) error
	CONNECT(path string, handler HandlerFunc) error

	GetRoutesByMethod(method string) *route
	// contains filtered or unexported methods
}

func NewRouter

func NewRouter() Router

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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