借鉴自这里
restful协议可以参考如下,当然最好的,看rails的rake routes,那个最标准了
URL HTTP Verb Functionality /object POST Creating Objects /object/objectId GET Retrieving Objects /object/objectId PUT Updating Objects /object GET Queries /object/objectId DELETE Deleting Objects
直接贴beego的代码
app.conf
appname = hello httpport = 8080 runmode = dev #RESTFul应用发送信息的时候是raw body,而不是普通的form表单,所以需要额外的读取body信息 copyrequestbody = true
router.go
package routers import ( "hello/controllers" "github.com/astaxie/beego" ) func init() { beego.RESTRouter("/object", &controllers.ObjectController{}) beego.Router("/", &controllers.MainController{}) }
ObjectController.go
package controllers import ( "fmt" "github.com/abbot/go-http-auth" "github.com/astaxie/beego" ) type ObjectController struct { beego.Controller } //API应用不需要模板渲染,所以关闭自动渲染 func (this *ObjectController) Prepare() { this.EnableRender = false } func (this *ObjectController) Post() { } func Secret(user, realm string) string { if user == "john" { // password is "hello" return "$1$dlPL2MqE$oQmn16q49SqdmhenQuNgs1" } return "" } //basic auth需要三方库来做 func (this *ObjectController) Get() { authenticate := auth.NewBasicAuthenticator("example.com", Secret) if username := authenticate.CheckAuth(this.Ctx.Request); username == "" { authenticate.RequireAuth(this.Ctx.ResponseWriter, this.Ctx.Request) } //url里面的参数这样获取this.Ctx.Input.Params[":objectId"] params := this.Ctx.Input.Params for key, value := range params { info := fmt.Sprintf("%s: %s\n", key, value) this.Ctx.WriteString(info) } } func (this *ObjectController) Put() { } func (this *ObjectController) Delete() { }
不解释了,都在代码里
时间: 2024-10-09 11:29:15