码迷,mamicode.com
首页 > Windows程序 > 详细

基于beego一键创建restful api

时间:2015-07-28 20:47:50      阅读:1177      评论:0      收藏:0      [点我收藏+]

标签:

借鉴自这里

 

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() {

}

 不解释了,都在代码里

基于beego一键创建restful api

标签:

原文地址:http://www.cnblogs.com/ziyouchutuwenwu/p/4684169.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!