Socket
Socket
Sign inDemoInstall

gopkg.in/go-siris/siris.v7

Package Overview
Dependencies
0
Alerts
File Explorer

Install Socket

Detect and block malicious and high-risk dependencies

Install

    gopkg.in/go-siris/siris.v7

Package siris is a fully-featured HTTP/2 backend web framework written entirely in Google’s Go Language. Source code and other details for the project are available at GitHub: The only requirement is the Go Programming Language, at least version 1.8 Example code: All HTTP methods are supported, developers can also register handlers for same paths for different methods. The first parameter is the HTTP Method, second parameter is the request path of the route, third variadic parameter should contains one or more context.Handler executed by the registered order when a user requests for that specific resouce path from the server. Example code: In order to make things easier for the user, Siris provides functions for all HTTP Methods. The first parameter is the request path of the route, second variadic parameter should contains one or more context.Handler executed by the registered order when a user requests for that specific resouce path from the server. Example code: A set of routes that are being groupped by path prefix can (optionally) share the same middleware handlers and template layout. A group can have a nested group too. `.Party` is being used to group routes, developers can declare an unlimited number of (nested) groups. Example code: Siris developers are able to register their own handlers for http statuses like 404 not found, 500 internal server error and so on. Example code: With the help of Siris's expressionist router you can build any form of API you desire, with safety. Example code: At the previous example, we've seen static routes, group of routes, subdomains, wildcard subdomains, a small example of parameterized path with a single known paramete and custom http errors, now it's time to see wildcard parameters and macros. Siris, like net/http std package registers route's handlers by a Handler, the Siris' type of handler is just a func(ctx context.Context) where context comes from github.com/go-siris/siris/context. Until go 1.9 you will have to import that package too, after go 1.9 this will be not be necessary. Siris has the easiest and the most powerful routing process you have ever meet. At the same time, Siris has its own interpeter(yes like a programming language) for route's path syntax and their dynamic path parameters parsing and evaluation, I am calling them "macros" for shortcut. How? It calculates its needs and if not any special regexp needed then it just registers the route with the low-level path syntax, otherwise it pre-compiles the regexp and adds the necessary middleware(s). Standard macro types for parameters: if type is missing then parameter's type is defaulted to string, so {param} == {param:string}. If a function not found on that type then the "string"'s types functions are being used. i.e: Besides the fact that Siris provides the basic types and some default "macro funcs" you are able to register your own too!. Register a named path parameter function: at the func(argument ...) you can have any standard type, it will be validated before the server starts so don't care about performance here, the only thing it runs at serve time is the returning func(paramValue string) bool. Example code: A path parameter name should contain only alphabetical letters, symbols, containing '_' and numbers are NOT allowed. If route failed to be registered, the app will panic without any warnings if you didn't catch the second return value(error) on .Handle/.Get.... Last, do not confuse ctx.Values() with ctx.Params(). Path parameter's values goes to ctx.Params() and context's local storage that can be used to communicate between handlers and middleware(s) goes to ctx.Values(), path parameters and the rest of any custom values are separated for your own good. Run Static Files Example code: More examples can be found here: https://github.com/go-siris/siris/tree/master/_examples/beginner/file-server Middleware is just a concept of ordered chain of handlers. Middleware can be registered globally, per-party, per-subdomain and per-route. Example code: Siris is able to wrap and convert any external, third-party Handler you used to use to your web application. Let's convert the https://github.com/rs/cors net/http external middleware which returns a `next form` handler. Example code: Siris supports 5 template engines out-of-the-box, developers can still use any external golang template engine, as `context.ResponseWriter()` is an `io.Writer`. All of these five template engines have common features with common API, like Layout, Template Funcs, Party-specific layout, partial rendering and more. Example code: View engine supports bundled(https://github.com/jteeuwen/go-bindata) template files too. go-bindata gives you two functions, asset and assetNames, these can be setted to each of the template engines using the `.Binary` func. Example code: A real example can be found here: https://github.com/go-siris/siris/tree/master/_examples/intermediate/view/embedding-templates-into-app. Enable auto-reloading of templates on each request. Useful while developers are in dev mode as they no neeed to restart their app on every template edit. Example code: Each one of these template engines has different options located here: https://github.com/go-siris/siris/tree/master/view . This example will show how to store and access data from a session. You don’t need any third-party library, but If you want you can use any session manager compatible or not. In this example we will only allow authenticated users to view our secret message on the /secret page. To get access to it, the will first have to visit /login to get a valid session cookie, which logs him in. Additionally he can visit /logout to revoke his access to our secret message. Example code: Running the example: But you should have a basic idea of the framework by now, we just scratched the surface. If you enjoy what you just saw and want to learn more, please follow the below links: Examples: Built'n Middleware: Community Middleware: Home Page:


Version published

Readme

Source

Logo

A fast, cross-platform and efficient web framework with robust set of well-designed features, written entirely in Go.

Build status Report card Support forum Examples Godocs Chat

Build your own web applications and portable APIs with the highest performance and countless potentials.

If you're coming from Node.js world, this is the expressjs++ equivalent for the Go Programming Language.

Table of contents

Installation

The only requirement is the Go Programming Language, at least version 1.8

$ go get -u github.com/go-siris/siris

Siris uses the vendor directory feature, so you get truly reproducible builds, as this method guards against upstream renames and deletes.

package main

import (
    "github.com/go-siris/siris"
    "github.com/go-siris/siris/context"
    "github.com/go-siris/siris/view"
)

// User is just a bindable object structure.
type User struct {
    Username  string `json:"username"`
    Firstname string `json:"firstname"`
    Lastname  string `json:"lastname"`
    City      string `json:"city"`
    Age       int    `json:"age"`
}

func main() {
    app := siris.New()

    // Define templates using the std html/template engine.
    // Parse and load all files inside "./views" folder with ".html" file extension.
    // Reload the templates on each request (development mode).
    app.AttachView(view.HTML("./views", ".html").Reload(true))

    // Regster custom handler for specific http errors.
    app.OnErrorCode(siris.StatusInternalServerError, func(ctx context.Context) {
    	// .Values are used to communicate between handlers, middleware.
    	errMessage := ctx.Values().GetString("error")
    	if errMessage != "" {
    		ctx.Writef("Internal server error: %s", errMessage)
    		return
    	}

    	ctx.Writef("(Unexpected) internal server error")
    })

    app.Use(func(ctx context.Context) {
    	ctx.Application().Logger().Info("Begin request for path: %s", ctx.Path())
    	ctx.Next()
    })

    // app.Done(func(ctx context.Context) {})

    // Method POST: http://localhost:8080/decode
    app.Post("/decode", func(ctx context.Context) {
    	var user User
    	ctx.ReadJSON(&user)
    	ctx.Writef("%s %s is %d years old and comes from %s", user.Firstname, user.Lastname, user.Age, user.City)
    })

    // Method GET: http://localhost:8080/encode
    app.Get("/encode", func(ctx context.Context) {
    	doe := User{
    		Username:  "Johndoe",
    		Firstname: "John",
    		Lastname:  "Doe",
    		City:      "Neither FBI knows!!!",
    		Age:       25,
    	}

    	ctx.JSON(doe)
    })

    // Method GET: http://localhost:8080/profile/anytypeofstring
    app.Get("/profile/{username:string}", profileByUsername)

    usersRoutes := app.Party("/users", logThisMiddleware)
    {
    	// Method GET: http://localhost:8080/users/42
    	usersRoutes.Get("/{id:int min(1)}", getUserByID)
    	// Method POST: http://localhost:8080/users/create
    	usersRoutes.Post("/create", createUser)
    }

    // Listen for incoming HTTP/1.x & HTTP/2 clients on localhost port 8080.
    app.Run(siris.Addr(":8080"), siris.WithCharset("UTF-8"))
}

func logThisMiddleware(ctx context.Context) {
    ctx.Application().Logger().Info("Path: %s | IP: %s", ctx.Path(), ctx.RemoteAddr())

    // .Next is required to move forward to the chain of handlers,
    // if missing then it stops the execution at this handler.
    ctx.Next()
}

func profileByUsername(ctx context.Context) {
    // .Params are used to get dynamic path parameters.
    username := ctx.Params().Get("username")
    ctx.ViewData("Username", username)
    // renders "./views/users/profile.html"
    // with {{ .Username }} equals to the username dynamic path parameter.
    ctx.View("users/profile.html")
}

func getUserByID(ctx context.Context) {
    userID := ctx.Params().Get("id") // Or convert directly using: .Values().GetInt/GetInt64 etc...
    // your own db fetch here instead of user :=...
    user := User{Username: "username" + userID}

    ctx.XML(user)
}

func createUser(ctx context.Context) {
    var user User
    err := ctx.ReadForm(&user)
    if err != nil {
    	ctx.Values().Set("error", "creating user, read and parse form failed. "+err.Error())
    	ctx.StatusCode(siris.StatusInternalServerError)
    	return
    }
    // renders "./views/users/create_verification.html"
    // with {{ . }} equals to the User object, i.e {{ .Username }} , {{ .Firstname}} etc...
    ctx.ViewData("", user)
    ctx.View("users/create_verification.html")
}

Feature Overview

FeatureMore Information
high performancebenchmark
Authenticationbasicauth oauth2 TODO JWT
Cachecache-markdown
Certificatesletsencrypt custom
Compressiongzip and deflate
Decode Json, Formsjson form
Encode Json, JsonP, XML, Forms, Markdownjson cache-markdown
Error handlingcustom [error handler] [panic handler]
http2 pushTODO add Documentation
LimitsRequestBody TODO add docu
Localizationi18n
Logger Enginesfile-logger request-logger
Routingrouting
Sessionssessions
Static Filesfile-server
Subdomains and Groupingsubdomains
Template HTML, django, pug(jade), handlebars, amberviews
ToolingTypescript integration + Web IDE
Websocketswebsockets

Documentation

Small but practical examples --they cover each feature.

Wanna create your own fast URL Shortener Service Using Siris? --click here to learn how.

Godocs --for deep understanding.

Hints --some performance hints and tooling.

Support

  • Chat Ask the Community for help
  • Post a feature request or report a bug, will help to make the framework even better.
  • :star: and watch the project, will notify you about updates.
  • :earth_americas: publish an article or share a tweet about siris.

Third Party Middleware

See THIRD-PARTY-MIDDLEWARE.md

Testing

The httptest package is your way for end-to-end HTTP testing, it uses the httpexpect library created by our friend, gavv.

A simple test is located to intermediate/httptest/main_test.go

Philosophy

The Siris philosophy is to provide robust tooling for HTTP, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs.

Siris does not force you to use any specific ORM or template engine. With support for the most popular template engines, you can quickly craft your perfect application.

People

The original author of Iris is @kataras. Before we forked to Siris.

However the real Success of Siris belongs to you with your bug reports and feature requests that made this Framework so Unique.

Version

Current: 7.3.4

Each new release is pushed to the master. It stays there until the next version. When a next version is released then the previous version goes to its own branch with gopkg.in as its import path (and its own vendor folder), in order to keep it working "for-ever".

Community members can request additional features or report a bug fix for a specific siris version.

Should I upgrade my Siris?

Developers are not forced to use the latest Siris version, they can use any version in production, they can update at any time they want.

Testers should upgrade immediately, if you're willing to use Siris in production you can wait a little more longer, transaction should be as safe as possible.

Where can I find older versions?

Each Siris version is independent. Only bug fixes, Router's API and experience are kept.

Previous versions can be found at releases page.

Previous Iris versions are archived at iris archive

License

Unless otherwise noted, the source files are distributed under the BSD-3-Clause License found in the LICENSE file.

Note that some third-party packages that you use with Siris may requires different license agreements.

FAQs

Last updated on 03 Sep 2017

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc