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

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

内容简介:前言工作需要,第一次使用 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 不熟,仅供学习。

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


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

查看所有标签

猜你喜欢:

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

你必须知道的213个C语言问题

你必须知道的213个C语言问题

范立锋、李世欣 / 人民邮电出版社 / 2010-6 / 45.00元

《你必须知道的213个C语言问题》精选了213个在C语言程序设计中经常遇到的问题,目的是帮助读者解决在C语言学习和开发中遇到的实际困难,提高读者学习和开发的效率。这些问题涵盖了C语言与软件开发、C语言基础、编译预处理、字符串、函数、键盘操作、文件、目录和磁盘、数组、指针和结构、DOS服务和BIOS服务、日期和时间、重定向I/O和进程命令、C语言开发常见错误及程序调试等内容,均是作者经过充分的调研,......一起来看看 《你必须知道的213个C语言问题》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

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

正则表达式在线测试

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

HSV CMYK互换工具