Go语言实现FastDFS分布式存储系统WebAPI网关

栏目: 服务器 · 发布时间: 7年前

内容简介:前言工作需要,第一次使用 Go 来实战项目。需求:采用 golang 实现一个 webapi 的中转网关,将一些资源文件通过 http 协议上传至 FastDFS 分布式文件存储系统。

前言

工作需要,第一次使用 Go 来实战项目。

需求:采用 golang 实现一个 webapi 的中转网关,将一些资源文件通过 http 协议上传至 FastDFS 分布式文件存储系统。

一、FastDFS 与 golang 对接的代码

github: https://github.com/weilaihui/fdfs_client

源代码可以 clone 下来看看,go 语法很简单

基本使用:(client_test.go 中有 test 案例代码)

package main

import (
    "fmt"
    "io/ioutil"
    "github.com/weilaihui/fdfs_client"
)

func main() {

    ff, _ := ioutil.ReadFile("1.jpg")
    fmt.Println("image len:", len(ff))
    /*
    hosts := []string{"10.0.1.32"}
    port := 22122
    minConns := 10
    maxConns := 150
    connPool,_ := fdfs_client.NewConnectionPool(hosts, port, minConns, maxConns)
    */
    path := "client.conf"
    fds, error := fdfs_client.NewFdfsClient(path)

    if fds == nil {
        fmt.Println("conn error: %s", error)
        var test string
        fmt.Scanln(&test)
        return
    }
    uploadResponse, err := fds.UploadByBuffer(ff, "jpg")

    if uploadResponse == nil {
        fmt.Println("upload error: %s", err)
        var test string
        fmt.Scanln(&test)
        return
    }
    fmt.Println("group name:", uploadResponse.GroupName)
    fmt.Println("remote file id:", uploadResponse.RemoteFileId)

    var test string
    fmt.Scanln(&test)
}

二、简单的 WebAPI 网关

beego 框架 go 圈很有名气,国内大学著作,考虑到这次工程较小,暂未使用起来。

go 实现一个 api 网关也是相当的简单:

package main

import (
    "fmt"
    "net/http"
 

    "io/ioutil"

)


func main() {
    http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
        rw.Write([]byte("Hello go web"))
    })
    http.HandleFunc("/upload", upload)
    http.ListenAndServe("localhost:8888", nil)
    fmt.Println("End.")
}


func upload(rw http.ResponseWriter, req *http.Request) {    
     fmt.Println("Header", req.Header)
     fmt.Println("Content-Type", req.Header.Get("Content-Type"))
     fmt.Println("Body", req.Body)

     // 获取 body 的全部内容
   /*

  len := req.ContentLength

    body := make([]byte, len)
    req.Body.Read(body)

    rw.Write([]byte("Response Body ...."))


   */

    data, _ := ioutil.ReadAll(req.Body)
}

PS:以上代码只是自己笔记使用,因为刚入手 go 不熟,仅供学习。

文件上传中转,如果是较大的文件,则采用将数据分片传输的方式进行。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

More Eric Meyer on CSS (Voices That Matter)

More Eric Meyer on CSS (Voices That Matter)

Eric A. Meyer / New Riders Press / 2004-04-08 / USD 45.00

Ready to commit to using more CSS on your sites? If you are a hands-on learner who has been toying with CSS and want to experiment with real-world projects that will enable you to see how CSS......一起来看看 《More Eric Meyer on CSS (Voices That Matter)》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具