Go实战--也许最快的Go语言Web框架kataras/iris初识(basic认证、Markdown、YAML、Json)

4 篇文章 0 订阅

生命不止,继续 go go go !!!

接下来,想跟大家一起分享一些golang语言成熟的、知名度比较高的web框架。

我们从iris web框架开始,开始呢,我们先不去计较和比较谁的速度快,谁的性能好,让我们先学习如何使用,积累到了一定程度后,再去进行测试各个框架的速度性能。

ris自称是Go语言中所有Web框架最快的,它的特点如下:

1.聚焦高性能 
2.健壮的静态路由支持和通配符子域名支持。 
3.视图系统支持超过5以上模板 
4.支持定制事件的高可扩展性Websocket API 
5.带有GC, 内存 & redis 提供支持的会话 
6.方便的中间件和插件 
7.完整 REST API 
8.能定制 HTTP 错误 
9.Typescript编译器 + 基于浏览器的编辑器 
10.内容 negotiation & streaming 
11.传送层安全性 
12.源码改变后自动加载 
13.OAuth, OAuth2 支持27+ API providers 
14.JSON Web Tokens

kataras/iris简介

github地址 
https://github.com/kataras/iris

Star: 7938

文档地址 
https://docs.iris-go.com/

描述 
关于kataras/iris的描述十分霸气: 
The fastest web framework for Go in (THIS) Earth. HTTP/2 Ready to GO. MVC when you need it. 
还是那句话,暂时不去计较,只是学习。

获取 
go get -u github.com/kataras/iris

快速开始

新建main.go 
新建views文件夹,在views中新建hello.html

main.go

package main

import "github.com/kataras/iris"

func main() {
    app := iris.New()
    app.RegisterView(iris.HTML("./views", ".html"))

    app.Get("/", func(ctx iris.Context) {
        ctx.ViewData("message", "Hello world!")
        ctx.View("hello.html")
    })

    app.Run(iris.Addr(":8080"))
}

hello.html

<html>
<head>
    <title>Hello Page</title>
</head>
<body>
    <h1>{{.message}}</h1>
</body>
</html>

运行,在浏览器输入http://localhost:8080/,得到运行结果。

basic认证

之前写过关于basic认证的文章: 
Go实战–通过basic认证的http(basic authentication)

package main

import (
    "time"

    "github.com/kataras/iris"
    "github.com/kataras/iris/context"
    "github.com/kataras/iris/middleware/basicauth"
)

func newApp() *iris.Application {
    app := iris.New()

    authConfig := basicauth.Config{
        Users:   map[string]string{"wangshubo": "wangshubo", "superWang": "superWang"},
        Realm:   "Authorization Required",
        Expires: time.Duration(30) * time.Minute,
    }

    authentication := basicauth.New(authConfig)

    app.Get("/", func(ctx context.Context) { ctx.Redirect("/admin") })


    needAuth := app.Party("/admin", authentication)
    {
        //http://localhost:8080/admin
        needAuth.Get("/", h)
        // http://localhost:8080/admin/profile
        needAuth.Get("/profile", h)

        // http://localhost:8080/admin/settings
        needAuth.Get("/settings", h)
    }

    return app
}

func main() {
    app := newApp()
    app.Run(iris.Addr(":8080"))
}

func h(ctx context.Context) {
    username, password, _ := ctx.Request().BasicAuth()
    ctx.Writef("%s %s:%s", ctx.Path(), username, password)
}

Markdown

Go实战–golang中使用markdown(russross/blackfriday)

package main

import (
    "time"

    "github.com/kataras/iris"
    "github.com/kataras/iris/context"

    "github.com/kataras/iris/cache"
)

var markdownContents = []byte(`## Hello Markdown

This is a sample of Markdown contents



Features
--------

All features of Sundown are supported, including:

*   **Compatibility**. The Markdown v1.0.3 test suite passes with
    the --tidy option.  Without --tidy, the differences are
    mostly in whitespace and entity escaping, where blackfriday is
    more consistent and cleaner.

*   **Common extensions**, including table support, fenced code
    blocks, autolinks, strikethroughs, non-strict emphasis, etc.

*   **Safety**. Blackfriday is paranoid when parsing, making it safe
    to feed untrusted user input without fear of bad things
    happening. The test suite stress tests this and there are no
    known inputs that make it crash.  If you find one, please let me
    know and send me the input that does it.

    NOTE: "safety" in this context means *runtime safety only*. In order to
    protect yourself against JavaScript injection in untrusted content, see
    [this example](https://github.com/russross/blackfriday#sanitize-untrusted-content).

*   **Fast processing**. It is fast enough to render on-demand in
    most web applications without having to cache the output.

*   **Routine safety**. You can run multiple parsers in different
    goroutines without ill effect. There is no dependence on global
    shared state.

*   **Minimal dependencies**. Blackfriday only depends on standard
    library packages in Go. The source code is pretty
    self-contained, so it is easy to add to any project, including
    Google App Engine projects.

*   **Standards compliant**. Output successfully validates using the
    W3C validation tool for HTML 4.01 and XHTML 1.0 Transitional.

    [this is a link](https://github.com/kataras/iris) `)


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

    app.Get("/", cache.Handler(10*time.Second), writeMarkdown)
    app.Run(iris.Addr(":8080"))
}

func writeMarkdown(ctx context.Context) {
    println("Handler executed. Content refreshed.")
    ctx.Markdown(markdownContents)
}

YAML

Go实战–go语言中使用YAML配置文件(与json、xml、ini对比) 
iris.yml

DisablePathCorrection: false
EnablePathEscape: false
FireMethodNotAllowed: true
DisableBodyConsumptionOnUnmarshal: true
TimeFormat: Mon, 01 Jan 2006 15:04:05 GMT
Charset: UTF-8

main.go

package main

import (
    "github.com/kataras/iris"
    "github.com/kataras/iris/context"
)

func main() {
    app := iris.New()
    app.Get("/", func(ctx context.Context) {
        ctx.HTML("<b>Hello!</b>")
    })

    app.Run(iris.Addr(":8080"), iris.WithConfiguration(iris.YAML("./iris.yml")))
}

Post Json

Go实战–net/http中JSON的使用(The way to go)

package main

import (
    "fmt"

    "github.com/kataras/iris"
    "github.com/kataras/iris/context"
)

type Company struct {
    Name  string
    City  string
    Other string
}

func MyHandler(ctx context.Context) {
    c := &Company{}
    if err := ctx.ReadJSON(c); err != nil {
        panic(err.Error())
    } else {
        fmt.Printf("Company: %#v", c)
        ctx.Writef("Company: %#v", c)
    }
}

func main() {
    app := iris.New()
    app.Post("/bind_json", MyHandler)
    app.Run(iris.Addr(":8080"))
}

curl命令行执行:

curl -d '{"Name":"vSuperWang", "City":"beijing", "Other":"shit"}' -H "Content-Type: application/json" -X POST http://localhost:8080/bind_json

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值