Go語言中Restful模式與Routes路由框架


1、用法:

  (1)導入包github.com/drone/routes

  (2)使用包中的New()方法建立一個routes.RouteMux對像的引用。其它也能理解為一個http.Handler,只是內部通過不同的方式如(GET、POST、PUT、DEL)進行了不同http.Handler的調用。

  (3)通過net/http包下的ListenAndServe(":8088",mux),去啟動一個Web服務。

  (4)通過Get和POST方式分別去請求結果。路徑中,將變量的部分替換成您要傳遞的值即可。如:mux.Post("/user/:uid/:age", edituser), 中可以通過POST請求發起地址:http://127.0.0.1:8088/user/song/23 去調用,此時系統將使用edituser方法,去處理代碼。edituser方法中,可以通過r.URL.Query().Get(":uid")去取得用戶id,如song。通過r.URL.Query().Get(":age")去取得年齡23.

2、代碼:

//用法:routes其實是個路由框架,當你使用Get請求或Post請求請求轉發好的地址時,它會根據相應路徑,進行值拆分。不同的請求方式,將使用不同的路由去拆分。
package main

import (
	"fmt"
	"net/http"
	"net/url"

	"github.com/drone/routes"
)

func getuser(w http.ResponseWriter, r *http.Request) {
	var params url.Values = r.URL.Query()
	var uid string = params.Get(":uid")
	fmt.Fprintln(w, "get a user ", uid, " success!")
}
func getuserAndAge(w http.ResponseWriter, r *http.Request) {
	var params url.Values = r.URL.Query()
	var uid string = params.Get(":uid")
	var age string = params.Get(":age")
	fmt.Fprintln(w, "get a user ", uid, " success! age is ", age)
}
func edituser(w http.ResponseWriter, r *http.Request) {
	var params url.Values = r.URL.Query()
	var uid string = params.Get(":uid")
	fmt.Fprintln(w, "edit a user ", uid, " success!")
}
func main() {
	fmt.Println("正在啟動WEB服務...")
	var mux *routes.RouteMux = routes.New()
	mux.Get("/user/:uid", getuser)
	mux.Get("/user/:uid/:age", getuserAndAge)
	mux.Post("/user/:uid", edituser)

	//http.Handle("/", mux)
	http.ListenAndServe(":8088", mux)
	fmt.Println("服務已停止")
}

3、運行結果:

D:/Application/Go/bin/go.exe build -i [D:/Projects/GoPath/source/demo/restful]
成功: 進程退出代碼 0.
D:/Projects/GoPath/source/demo/restful/restful.exe  [D:/Projects/GoPath/source/demo/restful]
正在啟動WEB服務...

4、測試:

        


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM