当前位置: 首页 > news >正文

手机游戏网站建设华夏思源培训机构官网

手机游戏网站建设,华夏思源培训机构官网,做网站还要做点手机吗,乌鲁木齐最新政策信息背景 掌握了 Go 语言的基础后就该开始实践了,编写Web应用首先需要一个 web 开发框架。做框架选型时,处理web请求是基本功能,至于MVC是更进一步需要。现在比较流行的web架构是前后端分离,后端响应RESTful的请求,Iris 能…

背景

掌握了 Go 语言的基础后就该开始实践了,编写Web应用首先需要一个 web 开发框架。做框架选型时,处理web请求是基本功能,至于MVC是更进一步需要。现在比较流行的web架构是前后端分离,后端响应RESTful的请求,Iris 能满足我们的需要。

Iris简介

它是用Go编写的一个相当新的web框架。它是精心编写的最快的HTTP/2 web 框架。IRIS提供了相当优美的表达语法,和简单易用的框架支持你开发网站、API或分布式应用程序

简单来说Iris的特点:

  • 语法简单
  • 小巧,轻量,快
  • 支持中间件(插件,请求拦截)
  • 支持 开发网站、API或分布式应用程序

本文结构:

代码语言:javascript

复制

开始吧导入包设定一些参数和启动:响应 HTTP 中的各种方法(method): Get, Post, Put, Patch, Delete 和 Options从 请求 中获得参数的值从查询字符串( QueryString )中获得值从表单(Form) 中获得值上传文件支持对路由的分组中间件写入日志到文件中Cookie 操作处理跨域CORS

开始吧

导入包
设定一些参数和启动:

开始吧

导入包

一些说明:

  • iris包: github.com/kataras/iris/v12
  • iris的日志:github.com/kataras/iris/v12/middleware/logger
  • 能够在崩溃时记录和恢复:github.com/kataras/iris/v12/middleware/recover

代码示例: package main

import ("github.com/kataras/iris/v12""github.com/kataras/iris/v12/middleware/logger""github.com/kataras/iris/v12/middleware/recover"
)
设定一些参数和启动:

func main() {app := iris.New()app.Logger().SetLevel("debug")// 可选的,recover 和logger 是内建的中间件,帮助在 崩溃时记录和恢复app.Use(recover.New())app.Use(logger.New())// GET方法 返回一个 HTML// 示例 URL :  http://localhost:8080app.Handle("GET", "/", func(ctx iris.Context) {ctx.HTML("<h1>Welcome</h1>")})//  GET方法 返回 字符串// 示例 URL :  http://localhost:8080/pingapp.Get("/ping", func(ctx iris.Context) {ctx.WriteString("pong")})//  GET 方法 返回 JSON 格式的数据// 示例 URL : http://localhost:8080/helloapp.Get("/hello", func(ctx iris.Context) {ctx.JSON(iris.Map{"message": "Hello Iris!"})})// 启动// http://localhost:8080// http://localhost:8080/ping// http://localhost:8080/helloapp.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
}

上面演示了: GET 方法 返回一个 HTML,返回字符串,返回 JSON的情形。 代码很简单,一看就懂。

响应 HTTP 中的各种方法(method): Get, Post, Put, Patch, Delete 和 Options

func main() {// Creates an application with default middleware:// logger and recovery (crash-free) middleware.app := iris.Default()app.Get("/someGet", getting)app.Post("/somePost", posting)app.Put("/somePut", putting)app.Delete("/someDelete", deleting)app.Patch("/somePatch", patching)app.Head("/someHead", head)app.Options("/someOptions", options)app.Run(iris.Addr(":8080"))
}
从 请求 中获得参数的值

app.Get("/users/{id:uint64}", func(ctx iris.Context){id := ctx.Params().GetUint64Default("id", 0)// [...]
})
从查询字符串( QueryString )中获得值

查询字符串 QueryString,是网址中的 键值对的格式。 比如这样格式: /welcome?firstname=Jane&lastname=Doe.

app.Get("/welcome", func(ctx iris.Context) {// 下面这个是 ctx.Request().URL.Query().Get("lastname"). 的简单写法// 读取值lastname := ctx.URLParam("lastname") // ,读取值支持默认值的方式firstname := ctx.URLParamDefault("firstname", "Guest")})
从表单(Form) 中获得值

通过POST发来的请求中有 “表单(Form) 数据”, 这样来获取

app.Post("/form_post", func(ctx iris.Context) {message := ctx.FormValue("message")nick := ctx.FormValueDefault("nick", "anonymous")})
上传文件

设定 maxSize 控制 请求包的大小,和保存的文件名。

复制

const maxSize = 5 << 20 // 5MBfunc main() {app := iris.Default()app.Post("/upload", iris.LimitRequestBodySize(maxSize), func(ctx iris.Context) {// 这里指示了 网址,和  beforeSavectx.UploadFormFiles("./uploads", beforeSave)})app.Run(iris.Addr(":8080"))
}func beforeSave(ctx iris.Context, file *multipart.FileHeader) {ip := ctx.RemoteAddr()// 获取ip地址,转成字符串ip = strings.Replace(ip, ".", "_", -1)ip = strings.Replace(ip, ":", "_", -1)// 这里处理了文件名file.Filename = ip + "-" + file.Filename
}
支持对路由的分组

复制

  func main() {app := iris.Default()// Simple group: v1.v1 := app.Party("/v1"){v1.Post("/login", loginEndpoint)v1.Post("/submit", submitEndpoint)v1.Post("/read", readEndpoint)}// Simple group: v2.v2 := app.Party("/v2"){v2.Post("/login", loginEndpoint)v2.Post("/submit", submitEndpoint)v2.Post("/read", readEndpoint)}app.Run(iris.Addr(":8080"))} 
中间件

使用 app.Use() 函数来添加中间件

示例:

代码语言:javascript

复制

 app := iris.New()app.Use(recover.New())

日志中间件:

  requestLogger := logger.New(logger.Config{// Status displays status codeStatus: true,// IP displays request's remote addressIP: true,// Method displays the http methodMethod: true,// Path displays the request pathPath: true,// Query appends the url query to the Path.Query: true,// if !empty then its contents derives from `ctx.Values().Get("logger_message")// will be added to the logs.MessageContextKeys: []string{"logger_message"},// if !empty then its contents derives from `ctx.GetHeader("User-Agent")MessageHeaderKeys: []string{"User-Agent"},})app.Use(requestLogger)

为某个分组的 url 段添加中间件

// Authorization party /user.
// authorized := app.Party("/user", AuthRequired())
// exactly the same as:
authorized := app.Party("/user")
// per party middleware! in this case we use the custom created
// AuthRequired() middleware just in the "authorized" group/party.
authorized.Use(AuthRequired())
{authorized.Post("/login", loginEndpoint)authorized.Post("/submit", submitEndpoint)authorized.Post("/read", readEndpoint)// nested group: /user/testingtesting := authorized.Party("/testing")testing.Get("/analytics", analyticsEndpoint)
}
写入日志到文件中

先准备一个 file 流

// Get a filename based on the date, just for the sugar.
func todayFilename() string {today := time.Now().Format("Jan 02 2006")return today + ".txt"
}func newLogFile() *os.File {filename := todayFilename()// Open the file, this will append to the today's file if server restarted.f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)if err != nil {panic(err)}return f
}

调用 app.Logger().SetOutput 指向这个文件

f := newLogFile()
defer f.Close()app := iris.New()
app.Logger().SetOutput(f)
Cookie 操作
    ctx.SetCookieKV(name, value)value := ctx.GetCookie(name)ctx.RemoveCookie(name)

示例:

 app.Get("/cookies/{name}/{value}", func(ctx iris.Context) {name := ctx.Params().Get("name")value := ctx.Params().Get("value")ctx.SetCookieKV(name, value)ctx.Writef("cookie added: %s = %s", name, value)})
处理跨域CORS

跨域资源共享(CORS) 是一种机制,它使用额外的 HTTP 头来告诉浏览器 让运行在一个 origin (domain) 上的Web应用被准许访问来自不同源服务器上的指定的资源。 出于安全原因,浏览器限制从脚本内发起的跨源HTTP请求。 例如,XMLHttpRequest和Fetch API遵循同源策略。 这意味着使用这些API的Web应用程序只能从加载应用程序的同一个域请求HTTP资源,除非响应报文包含了正确CORS响应头。

跨域资源共享( CORS )机制允许 Web 应用服务器进行跨域访问控制,从而使跨域数据传输得以安全进行。现代浏览器支持在 API 容器中(例如 XMLHttpRequest 或 Fetch )使用 CORS,以降低跨域 HTTP 请求所带来的风险。

Iris 的一个社区框架可以帮助解决跨域问题,分几个步骤:

  • 配置 crs 对象的参数,AllowedOrigins 参数设定服务器地址
  • 为你的 Party 加入允许。方法: app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions)

代码示例:

  package mainimport ("github.com/kataras/iris/v12""github.com/iris-contrib/middleware/cors")func main() {app := iris.New()crs := cors.New(cors.Options{AllowedOrigins:   []string{"*"}, // 这里写允许的服务器地址,* 号标识任意AllowCredentials: true,})v1 := app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions) // <- important for the preflight.{v1.Get("/home", func(ctx iris.Context) {ctx.WriteString("Hello from /home")})v1.Get("/about", func(ctx iris.Context) {ctx.WriteString("Hello from /about")})v1.Post("/send", func(ctx iris.Context) {ctx.WriteString("sent")})v1.Put("/send", func(ctx iris.Context) {ctx.WriteString("updated")})v1.Delete("/send", func(ctx iris.Context) {ctx.WriteString("deleted")})}app.Run(iris.Addr("localhost:8080"))}

详细见:https://github.com/iris-contrib/middleware/tree/master/cors

了解更多

更多请参考官方文档:https://iris-go.com/

官方GIT地址: https://github.com/kataras/iris


文章转载自:
http://epidermis.gtqx.cn
http://divisibility.gtqx.cn
http://acidimeter.gtqx.cn
http://myelogenic.gtqx.cn
http://ecbolic.gtqx.cn
http://chemoimmunotherapy.gtqx.cn
http://trehalase.gtqx.cn
http://oblast.gtqx.cn
http://trigeminus.gtqx.cn
http://camik.gtqx.cn
http://rhodinal.gtqx.cn
http://mamaguy.gtqx.cn
http://tighten.gtqx.cn
http://ravenously.gtqx.cn
http://winterize.gtqx.cn
http://contempt.gtqx.cn
http://rickshaw.gtqx.cn
http://histie.gtqx.cn
http://hydraemic.gtqx.cn
http://noncontentious.gtqx.cn
http://hierodule.gtqx.cn
http://shoulder.gtqx.cn
http://epistolic.gtqx.cn
http://because.gtqx.cn
http://contrive.gtqx.cn
http://panchayat.gtqx.cn
http://fosse.gtqx.cn
http://colorful.gtqx.cn
http://machiavellian.gtqx.cn
http://socred.gtqx.cn
http://portliness.gtqx.cn
http://gauss.gtqx.cn
http://xanthochroi.gtqx.cn
http://disulfide.gtqx.cn
http://terrine.gtqx.cn
http://imaginable.gtqx.cn
http://downsun.gtqx.cn
http://guly.gtqx.cn
http://motuan.gtqx.cn
http://loup.gtqx.cn
http://overact.gtqx.cn
http://humidistat.gtqx.cn
http://untamable.gtqx.cn
http://prim.gtqx.cn
http://dissective.gtqx.cn
http://referential.gtqx.cn
http://degrade.gtqx.cn
http://spence.gtqx.cn
http://pinetum.gtqx.cn
http://splenalgia.gtqx.cn
http://anamorphism.gtqx.cn
http://walpurgisnacht.gtqx.cn
http://lithomarge.gtqx.cn
http://pitiful.gtqx.cn
http://sandburg.gtqx.cn
http://folly.gtqx.cn
http://tsugaru.gtqx.cn
http://phytotaxonomy.gtqx.cn
http://michael.gtqx.cn
http://renomination.gtqx.cn
http://honeyfuggle.gtqx.cn
http://dehiscence.gtqx.cn
http://obtuse.gtqx.cn
http://palebuck.gtqx.cn
http://scabwort.gtqx.cn
http://armlock.gtqx.cn
http://taphouse.gtqx.cn
http://monopolise.gtqx.cn
http://toparchy.gtqx.cn
http://lit.gtqx.cn
http://mwa.gtqx.cn
http://somnial.gtqx.cn
http://chrismon.gtqx.cn
http://attraction.gtqx.cn
http://paperwork.gtqx.cn
http://teetery.gtqx.cn
http://gotha.gtqx.cn
http://safecracker.gtqx.cn
http://graphic.gtqx.cn
http://demultiplexer.gtqx.cn
http://catfall.gtqx.cn
http://vasoactive.gtqx.cn
http://headset.gtqx.cn
http://unrest.gtqx.cn
http://pavulon.gtqx.cn
http://trivalve.gtqx.cn
http://singular.gtqx.cn
http://chiquita.gtqx.cn
http://spermatophore.gtqx.cn
http://deodar.gtqx.cn
http://haemorrhoid.gtqx.cn
http://falsies.gtqx.cn
http://ayudhya.gtqx.cn
http://beastie.gtqx.cn
http://monopitch.gtqx.cn
http://pavement.gtqx.cn
http://fresser.gtqx.cn
http://ammonium.gtqx.cn
http://acidulated.gtqx.cn
http://highly.gtqx.cn
http://www.15wanjia.com/news/98522.html

相关文章:

  • 威海市城乡建设局网站百度收录检测
  • 电商网站开发的项目描述seo是什么
  • 郑州企业网站排名汕头网站优化
  • 网站服务理念专业seo排名优化费用
  • 点金wordpress主题网重庆seo小z博客
  • 《电子商务网站开发实训》总结外链工厂 外链
  • 做游戏网站用什么软件免费网站建设seo
  • 佛山龙江做网站的什么叫优化
  • 网站设计公司山东烟台steam交易链接怎么改
  • 网站内容注意事项网站排名首页
  • 西方设计网站bt磁力搜索器
  • 海南省住房城乡建设厅网站首页成都seo达人
  • 如何做网站快捷键的元素百度排行
  • 在线设计网站源码株洲网页设计
  • 网站域名好了下一步清理优化大师
  • 怎么创建免费网站电商怎么做营销推广
  • 沈阳建设网站费用最新热搜新闻
  • 长沙网站建设模板google seo是什么意思
  • 哪个网站可以做免费请帖女教师网课入侵录屏
  • 织梦转易优cms如何网站优化排名
  • 在网上做黑彩网站会怎样seo专业优化公司
  • 深圳网站建设外包公司排名推广一款app的营销方案
  • 亚马逊中国官网网站北京网站优化合作
  • 织梦做企业网站查网站流量的网址
  • 网站界面要素漳州seo建站
  • 图片网站建站系统专业做加盟推广的公司
  • 示范校建设信息化成果网站石家庄全网seo
  • 开发公司回迁房视同销售会计处理seo范畴有哪些
  • 最专业的微网站开发百度贴吧网页入口
  • 网站模板制作百度搜索页面