iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 16
1
Modern Web

Go!從無到打造最佳行動網站系列 第 16

Day16 純、手工系列 Go (BeeGo Request篇)(上)

beego
到第16天了,雖然每天好像都被文章追著跑,但是不知不覺中其實也寫了16篇,每一篇在寫的時候其實自己也在update自己的資料庫,其實很棒的呢~

BeeGo Request篇

Beego的功能其實真的蠻強大的,Go的Framework裡面還有幾個比較知名的框架,之後有機會的話再來研究研究,其時還是有許多的功能沒有介紹到,像是資料庫串接,這個部分好像也蠻重要的,不過越接近年底感覺事情越來越多,如果提早把一個小app寫完,再來寫串接db的部分。

這一篇大概是我之前在實作的時候,參考最多的部分,因為在post的時候遇到太多的問題,都會來找找看Request文件的部分。
今天會來將這些東西自己做的整理吧!

接收參數(GET/POST)

Beego 支援GET、POST,使用下面的方法來取得資料
大概講講解一下Golang的func的表達,以GetString(key string) string作為範例

  • GetString 為方法的名稱,goLang有規定func名稱一定字首要大寫
  • (key string) 為傳入的參數,並且宣告參數的型態,可以給func使用。
  • string 後面的表示回傳的型態會是一個字串
    回到正題,beego 提供了一些方法,來幫助使用者取得request func,提供以下方法(參考至官方文件)
GetString(key string) string
GetStrings(key string) []string
GetInt(key string) (int, error)
GetInt8(key string) (int8, error)
GetInt16(key string) (int16, error)
GetInt32(key string) (int32, error)
GetInt64(key string) (int64, error)
GetBool(key string) (bool, error)
GetFloat(key string) (float64, error)

Example

func (this *TeacherController) DelTeacherByTID() {
  tid := this.GetString(":teacherId")
  models.DeleteTeacher(tid)
  this.Data["json"] = map[string]string{"status": "success", "data": tid}
  this.ServeJSON()
}

這是我將之前的練習,在寫一個Teacher Controller,我們將要刪除的TeacherId透過網址列上的routing解析

/ironSchool/teacher/:teacherID

我們將職員編號帶入url中並且用http method delete傳送到伺服器,可以參考下方圖 (使用工具:Postman)

exampledel

Example 2

func (this *TeacherController) PostNewTeacher() {
  tName := this.GetString("TeacherName")
  tAge, _ := this.GetInt("TeacherAge")
  tTel := this.GetString("TeacherTel")
  newTeacherId := models.AddNewTeacher(models.Teacher{"", tName, tAge, tTel})
  this.Data["json"] = map[string]string{"data": newTeacherId}
  this.ServeJSON()
}

這範例是透過一個個參數慢慢取出來,當然你要做驗證是需要這樣做的!
或者是你可以透過ParseForm()這個func將有用的資料填入struct之中,不過注意Key與Value,是否拼錯,或是型態是否正確喔。

還有一些明天再戰!


上一篇
Day15 初次見面 應用程式介面 ApplicationProgrammingInterface (下)
下一篇
Day17 純、手工系列 Go (BeeGo Request篇)(下)
系列文
Go!從無到打造最佳行動網站30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言