package main
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
)
func main() {
s := g.Server()
// 普通返回
s.BindHandler("/", func(r *ghttp.Request) {
r.Response.Write("r.Response.write...")
r.Response.Writeln("r.Response.Writeln...")
r.Response.Writef("r.Response.Writef")
})
// 輸出數(shù)據(jù)后退出當(dāng)前服務(wù)
s.BindHandler("/exit", func(r *ghttp.Request) {
r.Response.WriteExit("xxx")
r.Response.Write("hello")
})
// 返回json格式
s.BindHandler("/json", func(r *ghttp.Request) {
r.Response.WriteJson(g.Map{
"code": 200,
"msg": "ok",
})
})
// 返回xml格式
s.BindHandler("/xml", func(r *ghttp.Request) {
r.Response.WriteXml(g.Map{
"code": 200,
"msg": "ok",
})
})
// 解析模板文件,也可以解析模板內(nèi)容,本例就直接使用解析模板內(nèi)容
s.BindHandler("/tpl", func(r *ghttp.Request) {
r.Response.WriteTplContent(` name: {{.name}} age: {{.age}}`, g.Map{
"name": "admin",
"age": 23,
})
})
// 解析模板文件或者模板內(nèi)容,返回解析后的內(nèi)容
s.BindHandler("/parse_tpl", func(r *ghttp.Request) {
content, err := r.Response.ParseTplContent(`name: {{.name}} age: {{.age}}`, g.Map{
"name": "admin",
"age": 23,
})
if err != nil {
panic(err)
}
// 返回解析回來(lái)的內(nèi)容
r.Response.Write(content)
})
s.Run()
}
模板解析
package main
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/ghttp"
)
func main() {
s := g.Server()
// 解析Config配置中的變量
// 訪問(wèn)默認(rèn)的配置管理(config.toml)對(duì)象配置項(xiàng)
s.BindHandler("/config", func(r *ghttp.Request) {
content := `{{.Config.server.host}} {{.Config.server.post}}`
r.Response.WriteTplContent(content, nil)
})
// 訪問(wèn)當(dāng)前請(qǐng)求的Cookie對(duì)象參數(shù)值。
s.BindHandler("/cookie", func(r *ghttp.Request) {
r.Cookie.Set("name", "admin")
content := `{{.Cookie.name}}`
r.Response.WriteTplContent(content, nil)
})
// 訪問(wèn)當(dāng)前請(qǐng)求的Session對(duì)象參數(shù)值。
s.BindHandler("/session", func(r *ghttp.Request) {
r.Session.Set("uid", "1001")
content := `{{.Session.uid}}`
r.Response.WriteTplContent(content, nil)
})
// 訪問(wèn)當(dāng)前Query String中的請(qǐng)求參數(shù)值。
s.BindHandler("/query", func(r *ghttp.Request) {
content := `{{.Query.name}}`
r.Response.WriteTplContent(content, nil)
})
// 訪問(wèn)當(dāng)前表單請(qǐng)求參數(shù)值。
s.BindHandler("/form", func(r *ghttp.Request) {
content := `{{.Form.username}}`
r.Response.WriteTplContent(content, nil)
})
// Request
s.BindHandler("/request", func(r *ghttp.Request) {
content := `{{.Request.Method}}`
r.Response.WriteTplContent(content, nil)
})
s.Run()
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。