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

简介: ris自称是Go语言中所有Web框架最快的,它的特点如下:1.聚焦高性能 2.健壮的静态路由支持和通配符子域名支持。 3.

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"))
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

hello.html

<html>
<head>
    <title>Hello Page</title>
</head>
<body>
    <h1>{{.message}}</h1>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

运行,在浏览器输入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)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

Markdown

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

package main

import (
    "time"

<span class="hljs-string">"github.com/kataras/iris"</span>
<span class="hljs-string">"github.com/kataras/iris/context"</span>

<span class="hljs-string">"github.com/kataras/iris/cache"</span>

)

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.

  • 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 `)

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

app.Get(<span class="hljs-string">"/"</span>, cache.Handler<span class="hljs-number">(10</span>*time.Second), writeMarkdown)
app.Run(iris.Addr(<span class="hljs-string">":8080"</span>))

}

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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")))
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

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"))
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

curl命令行执行:

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

这里写图片描述

目录
相关文章
|
7月前
|
算法 Java Go
【GoGin】(1)上手Go Gin 基于Go语言开发的Web框架,本文介绍了各种路由的配置信息;包含各场景下请求参数的基本传入接收
gin 框架中采用的路优酷是基于httprouter做的是一个高性能的 HTTP 请求路由器,适用于 Go 语言。它的设计目标是提供高效的路由匹配和低内存占用,特别适合需要高性能和简单路由的应用场景。
583 4
|
7月前
|
开发框架 前端开发 Go
【GoGin】(0)基于Go的WEB开发框架,GO Gin是什么?怎么启动?本文给你答案
Gin:Go语言编写的Web框架,以更好的性能实现类似Martini框架的APInet/http、Beego:开源的高性能Go语言Web框架、Iris:最快的Go语言Web框架,完备的MVC支持。
599 1
|
11月前
|
开发框架 JSON 中间件
Go语言Web开发框架实践:路由、中间件、参数校验
Gin框架以其极简风格、强大路由管理、灵活中间件机制及参数绑定校验系统著称。本文详解其核心功能:1) 路由管理,支持分组与路径参数;2) 中间件机制,实现全局与局部控制;3) 参数绑定,涵盖多种来源;4) 结构体绑定与字段校验,确保数据合法性;5) 自定义校验器扩展功能;6) 统一错误处理提升用户体验。Gin以清晰模块化、流程可控及自动化校验等优势,成为开发者的优选工具。
|
11月前
|
开发框架 安全 前端开发
Go Web开发框架实践:模板渲染与静态资源服务
Gin 是一个功能强大的 Go Web 框架,不仅适用于构建 API 服务,还支持 HTML 模板渲染和静态资源托管。它可以帮助开发者快速搭建中小型网站,并提供灵活的模板语法、自定义函数、静态文件映射等功能,同时兼容 Go 的 html/template 引擎,具备高效且安全的页面渲染能力。
|
11月前
|
开发框架 JSON 中间件
Go语言Web开发框架实践:使用 Gin 快速构建 Web 服务
Gin 是一个高效、轻量级的 Go 语言 Web 框架,支持中间件机制,非常适合开发 RESTful API。本文从安装到进阶技巧全面解析 Gin 的使用:快速入门示例(Hello Gin)、定义 RESTful 用户服务(增删改查接口实现),以及推荐实践如参数校验、中间件和路由分组等。通过对比标准库 `net/http`,Gin 提供更简洁灵活的开发体验。此外,还推荐了 GORM、Viper、Zap 等配合使用的工具库,助力高效开发。
|
人工智能 自然语言处理 JavaScript
测试工程师要失业?Magnitude:开源AI Agent驱动的端到端测试框架,让Web测试更智能,自动完善测试用例!
Magnitude是一个基于视觉AI代理的开源端到端测试框架,通过自然语言构建测试用例,结合推理代理和视觉代理实现智能化的Web应用测试,支持本地运行和CI/CD集成。
2104 15
测试工程师要失业?Magnitude:开源AI Agent驱动的端到端测试框架,让Web测试更智能,自动完善测试用例!
|
开发框架 搜索推荐 数据可视化
Django框架适合开发哪种类型的Web应用程序?
Django 框架凭借其强大的功能、稳定性和可扩展性,几乎可以适应各种类型的 Web 应用程序开发需求。无论是简单的网站还是复杂的企业级系统,Django 都能提供可靠的支持,帮助开发者快速构建高质量的应用。同时,其活跃的社区和丰富的资源也为开发者在项目实施过程中提供了有力的保障。
1045 157
|
12月前
|
JSON JavaScript 前端开发
Go语言JSON 序列化与反序列化 -《Go语言实战指南》
本文介绍了 Go 语言中使用 `encoding/json` 包实现 JSON 与数据结构之间的转换。内容涵盖序列化(`Marshal`)和反序列化(`Unmarshal`),包括基本示例、结构体字段标签的使用、控制字段行为的标签(如 `omitempty` 和 `-`)、处理 `map` 和切片、嵌套结构体序列化、反序列化未知结构(使用 `map[string]interface{}`)以及 JSON 数组的解析。最后通过表格总结了序列化与反序列化的方法及类型要求,帮助开发者快速掌握 JSON 数据处理技巧。
|
存储 JSON 安全
如何使用 JSON Web Tokens 进行身份验证?
总的来说,JWT 是一种强大而灵活的身份验证方式,通过正确使用和管理,可以为应用提供可靠的身份验证机制,同时提高系统的可扩展性和安全性。在实际应用中,需要根据具体的需求和场景,合理设计和实施 JWT 身份验证方案。
475 63
|
监控 Linux PHP
【02】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-2月12日优雅草简化Centos stream8安装zabbix7教程-本搭建教程非docker搭建教程-优雅草solution
【02】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-2月12日优雅草简化Centos stream8安装zabbix7教程-本搭建教程非docker搭建教程-优雅草solution
533 20

热门文章

最新文章