MCPcopy Index your code
hub / github.com/andeya/faygo

github.com/andeya/faygo @v1.4.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.4.0 ↗ · + Follow
3,319 symbols 10,827 edges 334 files 1,517 documented · 46%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Faygo report card github issues github closed issues GitHub release GoDoc view Go网络编程群

Faygo Favicon

Faygo is a fast and concise Go Web framework that can be used to develop high-performance web app(especially API) with fewer codes. Just define a struct Handler, Faygo will automatically bind/verify the request parameters and generate the online API doc. Go to \<User Manual>

简体中文

faygo index

faygo apidoc

faygo server

Latest version

Version

v1.2.0

Requirements

Go Version ≥ 1.8

Quick Start

  • Way 1: download source
go get -u -v github.com/andeya/faygo
go get -u -v github.com/andeya/fay
        fay command [arguments]

The commands are:
        new        create, compile and run (monitor changes) a new faygo project
        run        compile and run (monitor changes) an any existing go project

fay new appname [apptpl]
        appname    specifies the path of the new faygo project
        apptpl     optionally, specifies the faygo project template type

fay run [appname]
        appname    optionally, specifies the path of the new project

Features

  • One struct Handler can get more things:
  • Define Handler/Middleware
  • Bind and verify request parameters
  • Generate an online document for the Swagger 2.0 API
  • Database ORM mapping

  • Handler and Middleware are exactly the same, both implement the Handler interface (func orstruct), which together constitute the handler chain of the router.

  • Supports multiple network types:
Network types Configuration net_types
HTTP http
HTTPS/HTTP2(TLS) https
HTTPS/HTTP2(Let's Encrypt TLS) letsencrypt
HTTPS/HTTP2(Let's Encrypt TLS on UNIX socket) unix_letsencrypt
HTTP(UNIX socket) unix_http
HTTPS/HTTP2(TLS on UNIX socket) unix_https
  • Support single-service & single-listener, single-service & multi-listener, multi-service & multi-listener and so on. The config of multiple services is independent of each other
  • The high-performance router based on httprouter supports both chain and tree registration styles; supports flexible static file router (such as DirFS, RenderFS, MarkdownFS, etc.)
  • Support graceful shutdown and rebooting, provide fay tools which has new projects, hot compilation , meta programming function
  • Use the most powerful pongo2 as the HTML rendering engine
  • Support near-LRU memory caching (mainly used for static file cache)
  • Support cross-platform color log system, and has two output interface(console and file)
  • Support session management (If you use a persistent storage engine, you must use gob.Register() to register the relevant custom type before starting the service)
  • Support global gzip compression config
  • Support XSRF security filtering
  • Most features try to use simple ini configs to avoid unnecessary recompilation, and these profiles can be automatically assigned default values
  • Provide gorm, xorm, sqlx, directSQL, Websocket, ini, http client and many other commonly used expansion packages

faygo handler multi-usage

Simple example

package main

import (
    // "mime/multipart"
    "time"
    "github.com/andeya/faygo"
)

type Index struct {
    Id        int      `param:"<in:path> <required> <desc:ID> <range: 0:10>"`
    Title     string   `param:"<in:query> <nonzero>"`
    Paragraph []string `param:"<in:query> <name:p> <len: 1:10> <regexp: ^[\\w]*$>"`
    Cookie    string   `param:"<in:cookie> <name:faygoID>"`
    // Picture         *multipart.FileHeader `param:"<in:formData> <name:pic> <maxmb:30>"`
}

func (i *Index) Serve(ctx *faygo.Context) error {
    if ctx.CookieParam("faygoID") == "" {
        ctx.SetCookie("faygoID", time.Now().String())
    }
    return ctx.JSON(200, i)
}

func main() {
    app := faygo.New("myapp", "0.1")

    // Register the route in a chain style
    app.GET("/index/:id", new(Index))

    // Register the route in a tree style
    // app.Route(
    //     app.NewGET("/index/:id", new(Index)),
    // )

    // Start the service
    faygo.Run()
}

/*
http GET:
    http://localhost:8080/index/1?title=test&p=abc&p=xyz
response:
    {
        "Id": 1,
        "Title": "test",
        "Paragraph": [
            "abc",
            "xyz"
        ],
        "Cookie": "2016-11-13 01:14:40.9038005 +0800 CST"
    }
*/

All samples

Handler and middleware

Handler and middleware are the same, both implemente Handler interface!

  • function type
// Page handler doesn't contains API doc description
func Page() faygo.HandlerFunc {
    return func(ctx *faygo.Context) error {
        return ctx.String(200, "faygo")
    }
}

// Page2 handler contains API doc description
var Page2 = faygo.WrapDoc(Page(), "test page2 notes", "test")
  • struct type
// Param binds and validates the request parameters by Tags
type Param struct {
    Id    int    `param:"<in:path> <required> <desc:ID> <range: 0:10>"`
    Title string `param:"<in:query>"`
}

// Serve implemente Handler interface
func (p *Param) Serve(ctx *faygo.Context) error {
    return ctx.JSON(200,
        faygo.Map{
            "Struct Params":    p,
            "Additional Param": ctx.PathParam("additional"),
        }, true)
}

// Doc implemente API Doc interface (optional)
func (p *Param) Doc() faygo.Doc {
    return faygo.Doc{
        // Add the API notes to the API doc
        Note: "param desc",
        // declare the response content format to the API doc
        Return: faygo.JSONMsg{
            Code: 1,
            Info: "success",
        },
        // additional request parameter declarations to the API doc (optional)
        Params: []faygo.ParamInfo{
            {
                Name:  "additional",
                In:    "path",
                Model: "a",
                Desc:  "defined by the `Doc()` method",
            },
        },
    }
}

Filter function

The filter function must be HandleFunc type!

func Root2Index(ctx *faygo.Context) error {
    // Direct access to `/index` is not allowed
    if ctx.Path() == "/index" {
        ctx.Stop()
        return nil
    }
    if ctx.Path() == "/" {
        ctx.ModifyPath("/index")
    }
    return nil
}

Route registration

  • tree style
// New application object, params: name, version
var app1 = faygo.New("myapp1", "1.0")

// router
app1.Filter(Root2Index).
    Route(
        app1.NewNamedGET("test page", "/page", Page()),
        app1.NewNamedGET("test page2", "/page2", Page2),
        app1.NewGroup("home",
            app1.NewNamedGET("test param", "/param", &Param{
                // sets the default value in the API documentation for the request parameters (optional)
                Id:    1,
                Title: "test param",
            }),
        ),
    )
  • chain style
// New application object, params: name, version
var app2 = faygo.New("myapp2", "1.0")

// router
app2.Filter(Root2Index)
app2.NamedGET("test page", "/page", Page())
app2.NamedGET("test page2", "/page2", Page2)
app2.Group("home")
{
    app2.NamedGET("test param", "/param", &Param{
        // sets the default value in the API documentation for the request parameters(optional)
        Id:    1,
        Title: "test param",
    })
}

Shutdown and reboot

  • shutdown gracefully
kill [pid]
  • reboot gracefully
kill -USR2 [pid]

Configuration

  • Each instance of the application has a single config (file name format config/{appname}[_{version}].ini). Refer to the following:

``` net_types = http|https # List of network type: http | https | unix_http | unix_https | letsencrypt | unix_letsencrypt addrs = 0.0.0.0:80|0.0.0.0:443 # List of multiple listening addresses tls_certfile = # TLS certificate file path tls_keyfile = # TLS key file path letsencrypt_dir = # Let's Encrypt TLS certificate cache directory unix_filemode = 0666 # File permissions for UNIX listener, requires octal number http_redirect_https = false # Redirect from 'http://hostname:port1' to 'https://hostname:port2' read_timeout = 0s # Maximum duration for reading the full; ns|µs|ms|s|m|h request (including body) write_timeout = 0s # Maximum duration for writing the full; ns|µs|ms|s|m|h response (including body) multipart_maxmemory_mb = 32 # Maximum size of memory that can be used when receiving uploaded files slow_response_threshold= 0s # When response time > slow_response_threshold, log level = 'WARNING'; 0 means not limited; ns|µs|ms|s|m|h print_body = false # Form requests are printed in JSON format, but other types are printed as-is

[router] # Routing config section redirect_trailing_slash = true # Automatic redirection (for example, /foo/ -> /foo) redirect_fixed_path = true # Tries to fix the current request path, if no handle is registered for it handle_method_not_allowed = true # Returns 405 if the requested method does not exist, otherwise returns 404 handle_options = true # Automatic response OPTIONS request, you can set the default Handler in Faygo no_default_params = false # If true, don't assign default request parameter values based on initial parameter values of the routing handler default_upload = true # Automatically register the default router: /upload/filepath default_static = true # Automatically register the default router: /static/filepath

[xsrf] # XSRF security section enable = false # Whether enabled or not key = faygoxsrf # Encryption key expire_second = 3600 # Expire of XSRF token

[session] # Session section enable = false # Whether enabled or not provider = memory # Data storage name = faygosessionID # The client stores the name of the cookie provider_config = # According to the different engine settings different config information cookie_life_second = 0 # The default value is 0, which is the lifetime of the browser gc_life_second = 300 # The interval between triggering the GC max_life_second = 3600 # The session max lefetime auto_setcookie = true # Automatically set on the session cookie value, the general default true domain = # The domain name that is allowed to access this cookie enable_sid_in_header = false # Whether to write a session ID to the header name_in_header = Faygosessionid # The name of the header when the session ID is written to the header enable_sid_in_urlquery = false # Whether to write the session ID to the URL Query params

[apidoc] # API documentation section enable = true # Whether enabled or not path = /apidoc # The URL path nolimit = false # If true, access is not restricted real_ip = false # If true, means verifying the real IP of the visitor whitelist = 192.*|202.122.246.170 # whitelist=192.*|202.122.246.170 means: only IP addresses that are prefixed with 192. or equal to 202.122.246.170 are allowed desc = # Description of the application email = # Technician's Email terms_url =

Extension points exported contracts — how you extend this code

Handler (Interface)
Handler is the main Faygo Handler interface. [6 implementers]
handler.go
Backend (Interface)
Backend is the interface which a log backend need to implement to be able to be used as a logging backend. [7 implementers]
logging/backend.go
Store (Interface)
Store contains all data for one session process with specific id. [10 implementers]
session/session.go
Schedule (Interface)
The Schedule describes a job's duty cycle. [6 implementers]
ext/cron/cron.go
KV (Interface)
(no doc) [15 implementers]
apiware/util.go
Barcode (Interface)
a rendered and encoded barcode [4 implementers]
ext/barcode/barcode.go
INode (Interface)
(no doc) [42 implementers]
pongo2/parser.go
Renderer (Interface)
Renderer is the rendering interface. This is mostly of interest if you are implementing a new rendering format. When a [2 …
markdown/markdown.go

Core symbols most depended-on inside this repo

WriteString
called by 316
pongo2/template.go
call
called by 243
pongo2/tags_macro.go
Close
called by 234
logging/backend.go
Error
called by 210
ext/db/xorm/logger.go
Error
called by 182
pongo2/error.go
Errorf
called by 170
ext/db/xorm/logger.go
Fatal
called by 161
logging/logger.go
AsValue
called by 120
pongo2/value.go

Shape

Function 1,546
Method 1,357
Struct 310
TypeAlias 53
Interface 34
FuncType 19

Languages

Go92%
TypeScript8%

Modules by API surface

_syso/jquery.min.js75 symbols
samples/directsqlx/static/jQuery-2.1.4.min.js64 symbols
samples/directsql/static/jQuery-2.1.4.min.js64 symbols
samples/demo/static/jQuery-2.1.4.min.js64 symbols
context_input.go64 symbols
fs.go60 symbols
logging/color/color.go58 symbols
markdown/markdown.go56 symbols
pongo2/filters_builtin.go53 symbols
markdown/html.go52 symbols
faygo.go49 symbols
ext/websocket/conn.go49 symbols

For agents

$ claude mcp add faygo \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact