一、httplib
1、配置文件解析
这是一个用来解析文件的库,它的设计思路来自于 database/sql
,目前支持解析的文件格式有 ini、json、xml、yaml,可以通过如下方式进行安装:
go;gutter:false;
go get github.com/astaxie/beego/config</p>
<pre><code>
如果你使用xml 或者 yaml 驱动就需要手工安装引入包
;gutter:false;
go get -u github.com/astaxie/beego/config/xml
2、始何使用
首先初始化一个解析器对象
go;gutter:false;
iniconf, err := NewConfig("ini", "testini.conf")
if err != nil {
t.Fatal(err)
}</p>
<pre><code>
然后通过对象获取数据
;gutter:false;
iniconf.String("appname")
解析器对象支持的函数有如下:
- Set(key, val string) error
- String(key string) string
- Int(key string) (int, error)
- Int64(key string) (int64, error)
- Bool(key string) (bool, error)
- Float(key string) (float64, error)
- DIY(key string) (interface{}, error)
ini 配置文件支持 section 操作,key通过 section::key
的方式获取
例如下面这样的配置文件
go;gutter:false;
[demo]
key1 = "asta"
key2 = "xie"</p>
<pre><code>
那么可以通过
.String("demo::key2") 获取值.
如何获取环境变量
config 模块支持环境变量配置,对应配置项 Key 格式为
${环境变量名} ,则 Value = os.Getenv('环境变量名')。
同时可配置默认值,当环境变量无此配置或者环境变量值为空时,则优先使用默认值。包含默认值的 Key 格式为
${GOPATH||/home/workspace/go/} ,使用
||分割环境变量和默认值。
**注意** 获取环境变量值仅仅是在配置文件解析时处理,而不会在调用函数获取配置项时实时处理。
示例:
controllers/testHttpLib.go
;gutter:false;
package controllers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/httplib"
)
type TestHttpLibController struct {
beego.Controller
}
func (c *TestHttpLibController) Get() {
req := httplib.Get("http://www.baidu.com")
str, err := req.String()
if err != nil {
panic(err)
}
//获取网站源代码
//c.Ctx.WriteString("start")
//直接打开网站
c.Ctx.WriteString(str)
}
routers/router.go
go;gutter:false;
package routers</p>
<p>import (
"web/controllers"</p>
<pre><code>"github.com/astaxie/beego"
</code></pre>
<p>)</p>
<p>func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/test_httplib", &controllers.TestHttpLibController{}, "get:Get;post:Post")
}</p>
<pre><code>
执行结果: 直接打开网站
![Go语言之高级篇beego框架之config、httplib、context](https://johngo-pic.oss-cn-beijing.aliyuncs.com/articles/20230526/1053682-20190216094752687-1910444340.png)
二、context
**1、上下文模块**
上下文模块主要是针对 HTTP 请求中,request 和 response 的进一步封装,他包括用户的输入和输出,用户的输入即为 request,context 模块中提供了 Input 对象进行解析,用户的输出即为 response,context 模块中提供了 Output 对象进行输出。
## 2、context对象
context 对象是对 Input 和 Output 的封装,里面封装了几个方法:
* Redirect
* Abort
* WriteString
* GetCookie
* SetCookie
context 对象是 Filter 函数的参数对象,这样你就可以通过 filter 来修改相应的数据,或者提前结束整个的执行过程。
## Output 对象
Output 是针对 Response 的封装,里面提供了很多方便的方法:
* Header 设置输出的 header 信息,例如
("Server","beego")
* Body 设置输出的内容信息,例如
([]byte("astaxie"))
* Cookie 设置输出的 cookie 信息,例如
("sessionID","beegoSessionID")
* Json 把 Data 格式化为 Json,然后调用 Body 输出数据
* Jsonp 把 Data 格式化为 Jsonp,然后调用 Body 输出数据
* Xml 把 Data 格式化为 Xml,然后调用 Body 输出数据
* Download 把 file 路径传递进来,然后输出文件给用户
* ContentType 设置输出的 ContentType
* SetStatus 设置输出的 status
* Session 设置在服务器端保存的值,例如
("username","astaxie"),这样用户就可以在下次使用的时候读取
* IsCachable 根据 status 判断,是否为缓存类的状态
* IsEmpty 根据 status 判断,是否为输出内容为空的状态
* IsOk 根据 status 判断,是否为 200 的状态
* IsSuccessful 根据 status 判断,是否为正常的状态
* IsRedirect 根据 status 判断,是否为跳转类的状态
* IsForbidden 根据 status 判断,是否为禁用类的状态
* IsNotFound 根据 status 判断,是否为找不到资源类的状态
* IsClientError 根据 status 判断,是否为请求客户端错误的状态
* IsServerError 根据 status 判断,是否为服务器端错误的状态
获取IP地址和端口
示例:
controllers/testContext.go
;gutter:false;
package controllers
import (
"strconv"
"github.com/astaxie/beego"
)
type TestContextController struct {
beego.Controller
}
func (c *TestContextController) Get() {
c.Ctx.WriteString(c.Ctx.Input.IP() + ":" + strconv.Itoa(c.Ctx.Input.Port()))
}
routers/router.go
go;gutter:false;
package routers</p>
<p>import (
"web/controllers"</p>
<pre><code>"github.com/astaxie/beego"
</code></pre>
<p>)</p>
<p>func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/test_context", &controllers.TestContextController{}, "get:Get;post:Post")
}</p>
<pre><code>
执行结果:
;gutter:true;
http://127.0.0.1:8080/test_context
返回结果:
127.0.0.1:8080
Input 对象
go;gutter:false;
Input 对象是针对 request 的封装,里面通过 reqeust 实现很多方便的方法,具体如下:</p>
<p>Protocol</p>
<p>获取用户请求的协议,例如 HTTP/1.0</p>
<p>Uri</p>
<p>用户请求的 RequestURI,例如 /hi?id=1001</p>
<p>Url</p>
<p>请求的 URL 地址,例如 /hi</p>
<p>Site</p>
<p>请求的站点地址,scheme+doamin 的组合,例如 http://beego.me</p>
<p>Scheme</p>
<p>请求的 scheme,例如 "http" 或者 "https"</p>
<p>Domain</p>
<p>请求的域名,例如 beego.me</p>
<p>Host</p>
<p>请求的域名,和 domain 一样</p>
<p>Method</p>
<p>请求的方法,标准的 HTTP 请求方法,例如 GET、POST 等</p>
<p>Is</p>
<p>判断是否是某一个方法,例如 Is("GET") 返回 true</p>
<p>IsAjax</p>
<p>判断是否是 AJAX 请求,如果是返回 true,不是返回 false</p>
<p>IsSecure</p>
<p>判断当前请求是否 HTTPS 请求,是返回 true,否返回 false</p>
<p>IsWebsocket</p>
<p>判断当前请求是否 Websocket 请求,如果是返回 true,否返回 false</p>
<p>IsUpload</p>
<p>判断当前请求是否有文件上传,有返回 true,否返回 false</p>
<p>IP</p>
<p>返回请求用户的 IP,如果用户通过代理,一层一层剥离获取真实的 IP</p>
<p>Proxy</p>
<p>返回用户代理请求的所有 IP</p>
<p>Refer</p>
<p>返回请求的 refer 信息</p>
<p>SubDomains</p>
<p>返回请求域名的根域名,例如请求是 blog.beego.me,那么调用该函数返回 beego.me</p>
<p>Port</p>
<p>返回请求的端口,例如返回 8080</p>
<p>UserAgent</p>
<p>返回请求的 UserAgent,例如 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36</p>
<p>Param</p>
<p>在路由设置的时候可以设置参数,这个是用来获取那些参数的,例如 Param(":id"),返回12</p>
<p>Query</p>
<p>该函数返回 Get 请求和 Post 请求中的所有数据,和 PHP 中 $_REQUEST 类似</p>
<p>Header</p>
<p>返回相应的 header 信息,例如 Header("Accept-Language"),就返回请求头中对应的信息 zh-CN,zh;q=0.8,en;q=0.6</p>
<p>Cookie</p>
<p>返回请求中的 cookie 数据,例如 Cookie("username"),就可以获取请求头中携带的 cookie 信息中 username 对应的值</p>
<p>Session</p>
<p>session 是用户可以初始化的信息,默认采用了 beego 的 session 模块中的 Session 对象,用来获取存储在服务器端中的数据。</p>
<p>Body</p>
<p>返回请求 Body 中数据,例如 API 应用中,很多用户直接发送 json 数据包,那么通过 Query 这种函数无法获取数据,就必须通过该函数获取数据。该函数已经 beego 1.5 版本之后删除,目前可以通过 RequestBody 获取数据。</p>
<p>GetData</p>
<p>用来获取 Input 中 Data 中的数据</p>
<p>SetData</p>
<p>用来设置 Input 中 Data 的值,上面 GetData 和这个函数都是用来方便用户在 Filter 中传递数据到 Controller 中来执行</p>
<pre><code>
Query方法
示例:
controllers/testContext.go
;gutter:false;
package controllers
import (
"strconv"
"github.com/astaxie/beego"
)
type TestContextController struct {
beego.Controller
}
func (c *TestContextController) Get() {
c.Ctx.WriteString(c.Ctx.Input.IP() + ":" + strconv.Itoa(c.Ctx.Input.Port()))
//Query方法
c.Ctx.WriteString(c.Ctx.Input.Query("name")) //等价于php中的 $_REQUEST["name"]
}
routers/router.go
go;gutter:false;
package routers</p>
<p>import (
"web/controllers"</p>
<pre><code>"github.com/astaxie/beego"
</code></pre>
<p>)</p>
<p>func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/test_context", &controllers.TestContextController{}, "get:Get;post:Post")
}</p>
<pre><code>
执行结果:
;gutter:true;
http://127.0.0.1:8080/test_context?name=nulige
返回结果:
127.0.0.1:8080nulige
另外一种方法:
示例:
controllers/testContext.go
go;gutter:false;
package controllers</p>
<p>import (
"strconv"</p>
<pre><code>"github.com/astaxie/beego"
</code></pre>
<p>)</p>
<p>type TestContextController struct {
beego.Controller
}</p>
<p>func (c *TestContextController) Get() {
c.Ctx.WriteString(c.Ctx.Input.IP() + ":" + strconv.Itoa(c.Ctx.Input.Port()))</p>
<pre><code>//Query方法
c.Ctx.WriteString(c.Ctx.Input.Query("name")) //等价于php中的 $_REQUEST["name"]
m := make(map[string]float64)
m["zhangsan"] = 98.7
c.Ctx.Output.JSON(m, false, false)
</code></pre>
<p>}</p>
<pre><code>
routers/router.go
;gutter:false;
package routers
import (
"web/controllers"
"github.com/astaxie/beego"
)
func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/test_context", &controllers.TestContextController{}, "get:Get;post:Post")
}
执行结果:
go;gutter:true;
http://127.0.0.1:8080/test_context</p>
<p>返回结果:</p>
<pre><code>
</code></pre>
<p>127.0.0.1:8080{"zhangsan":98.7}
Original: https://www.cnblogs.com/nulige/p/10375774.html
Author: 努力哥
Title: Go语言之高级篇beego框架之config、httplib、context
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/535780/
转载文章受原作者版权保护。转载请注明原作者出处!