Go Phabricator API 代码/程序创建task/提交文件到Phabricator

Go Phabricator API 代码/程序创建task/提交文件到Phabricator

Creat Task or upload file to phabricator with code in go

之前写一个服务往phabricator 上提交task,上传文件;当时查了好久,发现官方文档很不明确,而网上又几乎没有资料,所以把最终写的整理一下给需要的做一个参考。
Several days ago,I have writing a service to submit tasks or upload files to the phabricator.At that time , search for a long time, found that the official document is not very clear, and almost no information on the Internet, so share something about this.

upload file/image or other info to phabricator by program in Go
Go语言,通过程序往phabricator上传文件/图片,新建task.

最终是要在phabricator上提交一个task,func3,通过调用调用func1,上传一个file,通过func2,获取这个file的id。在func3中创建task的时候,可以通过“F【 + id】”的格式引用这个文件或者图片。
The final target is to submit a task to the phabricator. Func3, by calling func1 upload a file, through func2, get the id of this file. In the func3 create a task, you can use "F [+ id]" format to quoted the file(or picture).

上传文件

upload file

注意 phabricator接收base64数据,而且不要开头的格式声明部分,即只要“,”后边的。
Pay attention,phabricator receive a data of base64 format,and deny the chars befor ",".


//1,文件上传:file.upload ,拿回来phid;在task里可以通过phid引用。
//1,upload file. api:file.upload. Get back the phid of this file which can be quoted in a task page。
func UploadFile(imageBase64List [imageMaxNum]string) ([]string, error) {
    phidList := make([]string, 0)
    urlStr := "https://ph.com/api/file.upload"

    for _, imageBase64 := range imageBase64List {
        if imageBase64 == "" {
            continue
        }
        //截取“,”后边的字符串,
        //Get chars after ","
        imageData := strings.Split(imageBase64, ",")
        if len(imageData) != 2 || !utils.JudgeBase64(imageData[1]) {
            return phidList, errors.New("图片数据格式错误")
        }
        form := url.Values{}
        form.Add("data_base64", imageData[1])

        req, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(form.Encode()))
        q := req.URL.Query()
        q.Set("api.token", common.Config.ApiToken)
        req.URL.RawQuery = q.Encode()
        req.Header.Add("content-type", "application/x-www-form-urlencoded")

        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            return phidList, err
        }
        defer resp.Body.Close()

        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            return phidList, err
        }
        //解析body,并且添加到切片
        //Unmarshal body and add to slice
        var uploadResp UploadFileResp
        if err := json.Unmarshal(body, &uploadResp); err != nil {
            err := errors.New("文件上传时发生未知错误:" + err.Error())
            return phidList, err
        }
        phidList = append(phidList, uploadResp.Result)
    }
    return phidList, nil
}

根据文件的phid获取id

get the id of file by phid


//  2,获取文件/图片id:file.info 拿回来一个file id
//  2,get the id of file/image though file.info .
func getImageId(phidList []string) (imageIdlist []string, err error) {
    imageIdList := make([]string, 0)
    urlStr := "https://ph.com/api/file.info"

    for _, phid := range phidList {
        if phid == "" {
            continue
        }

        form := url.Values{}
        form.Add("phid", phid)
        req, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(form.Encode()))
        req.Header.Add("content-type", "application/x-www-form-urlencoded")
        q := req.URL.Query()
        q.Set("api.token", common.Config.ApiToken)
        req.URL.RawQuery = q.Encode()

        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            return imageIdList, err
        }
        defer resp.Body.Close()

        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            return imageIdList, err
        }
        var findImageResp FindImageIdResp
        if err := json.Unmarshal(body, &findImageResp); err != nil {
            err := errors.New("获取文件信息时发生未知错误" + err.Error())
            return imageIdList, err
        }
        imageIdList = append(imageIdList, findImageResp.Result.ObjectName)
    }
    return imageIdList, nil
}


入口函数

entrance func

conduit api 测试页面参数示例
conduit pages api test parameters example

    [   {       "type":"title",         "value":"Test API in conduit"   }, 
    {       "type":"view",          "value":"users" },
    {       "type":"projects.add",          "value":["bug_管理","生 产环境"]      },  
    {       "type":"description",       "value":"Nothing , need not to be concerned. "  },
    {       "type":"priority",      "value":"low"},
    {       "type":"custom.mq.customer_id_and_name","value":"coustomId and name"}
 ]

接收参数,并调用fun1、fun2,最终提交task。
Get parameters ,call func1、func2,submit a task at last。


// 3,接收bug信息,上传文件/图片,获取文件id,提交bug信息,返回提示信息。
// 3,receive the infomation from pages,get the id of file/image ,submit info and sendback tips.
func ReceiptBugInfo(w http.ResponseWriter, r *http.Request) {
    var reqInfo ReceiptBugInfoRequest
    if err := utils.BindJSON(r, &reqInfo); err != nil {
        render.BindError(w, r, err)
        return
    }

    desc := reqInfo.Desc + "\n\n终端信息:" + reqInfo.EndPointInfo + "\nbug提交位置参考路径:" + reqInfo.BugPageUrl
    customIdAndName := "用户名:" + reqInfo.CustomerName + "    用户ID:" + reqInfo.CustomerId + "    租户ID" + reqInfo.TenantId
    desc += "\n" + customIdAndName + "\n"
    //检查,不为空则调用getImgId,并拼入desc
    if reqInfo.ImagesData[0] != "" {
        phidList, err := UploadFile(reqInfo.ImagesData)
        if err != nil {
            render.InternalError(w, r, err)
        }
        imageIdSlice, err := getImageId(phidList)
        if err != nil {
            render.InternalError(w, r, err)
        }
        for _, images := range imageIdSlice {
            if images == "" {
                break
            }
            desc += "\nbug截图:\n{" + images + "}"
        }
    }

    urlStr := "https://ph.com/api/maniphest.edit"

    form := url.Values{}
    form.Add("transactions[0][type]", "title")
    form.Add("transactions[0][value]", reqInfo.Title)
    form.Add("transactions[1][type]", "description")
    form.Add("transactions[1][value]", desc)
    form.Add("transactions[2][type]", "priority")
    form.Add("transactions[2][value]", reqInfo.Priority)
    form.Add("transactions[3][type]", "projects.add")
    form.Add("transactions[3][value][0]", "bug_管理")
    form.Add("transactions[3][value][1]", "生产环境")
    form.Add("transactions[4][type]", "space")
    form.Add("transactions[4][value]", "PHID-SPCE-cnulhg6i3r4m5evgb4wc")

    req, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(form.Encode()))
    req.Header.Add("content-type", "application/x-www-form-urlencoded")
    q := req.URL.Query()
    q.Set("api.token", common.Config.ApiToken)
    req.URL.RawQuery = q.Encode()

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        render.InternalNetError(w, r, err)
    }
    defer resp.Body.Close()

    //解析这个body,error不为空则报错,图片上传.
    //Unmarshal body,if error is not nil,panic.else upload file/image.
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        render.InternalError(w, r, err)
        return
    }
    var bugInfoResp BugInfoUploadResp
    if err := json.Unmarshal(body, &bugInfoResp); err != nil {
        error := errors.New("解析反馈信息时发生未知错误" + err.Error())
        render.InternalError(w, r, error)
        return
    }

    if bugInfoResp.ErrorCode != "" {
        err := errors.New("提交信息时发生未知错误" + bugInfoResp.ErrorInfo)
        render.InternalError(w, r, err)
        return
    }

    render.Success(w, r)
}

结构体定义如下

definition struct as below


type BugInfoUploadResp struct {
    Result    BugRespResult `json:"result" binding:"omitempty`
    ErrorCode string        `json:"error_code" binding:"omitempty`
    ErrorInfo string        `json:"error_info" binding:"omitempty`
}

type BugRespResult struct {
    Object       BugRespObject `json:"object" binding:"omitempty`
    Transactions Phids         `json:"transactions" binding:"omitempty`
}

type BugRespObject struct {
    Id   int    `json:"id" binding:"omitempty`
    Phid string `json:"phid" binding:"omitempty`
}

type Phids []Phid

type Phid struct {
    Phid string `json:"phid" binding:"omitempty`
}

type UploadFileResp struct {
    Result    string `json:"result" binding:"omitempty`
    ErrorCode string `json:"error_code" binding:"omitempty`
    ErrorInfo string `json:"error_info" binding:"omitempty`
}

type FindImageIdResp struct {
    Result    ImgIdRespInfo `json:"result" binding:"omitempty`
    ErrorCode string        `json:"error_code" binding:"omitempty`
    ErrorInfo string        `json:"error_info" binding:"omitempty`
}

type ImgIdRespInfo struct {
    Id           string `json:"id" binding:"omitempty"`
    Phid         string `json:"phid" binding:"omitempty"`
    ObjectName   string `json:"objectName" binding:"omitempty"`
    Name         string `json:"name" binding:"omitempty"`
    MimeType     string `json:"mimeType" binding:"omitempty"`
    ByteSize     string `json:"byteSize" binding:"omitempty"`
    AuthorPHID   string `json:"authorPHID" binding:"omitempty"`
    DateCreated  string `json:"dateCreated" binding:"omitempty"`
    DateModified string `json:"dateModified" binding:"omitempty"`
    Uri          string `json:"uri" binding:"omitempty"`
}

type ReceiptBugInfoRequest struct {
    TenantId     string    `json:"tenantId" binding:"required"`
    CustomerName string    `json:"customerName" binding:"required"`
    CustomerId   string    `json:"customerId" binding:"required"`
    Desc         string    `json:"desc" binding:"required"`
    Title        string    `json:"title" binding:"required"`
    Priority     string    `json:"priority" binding:"required"`
    EndPointInfo string    `json:"endPointInfo" binding:"required"`
    BugPageUrl   string    `json:"bugPageUrl" binding:"omitempty`
    ImagesData   ImageList `json:"imageData" binding:"omitempty"`
}

type ImageList [imageMaxNum]string

//反馈,图片最大支持数目。
//feedback,the max number of image
const imageMaxNum = 10

转载注明出处----名白
http://www.cnblogs.com/mingbai/p/GoPhabricator.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容