首页 技术 正文
技术 2022年11月6日
0 收藏 654 点赞 1,028 浏览 1645 个字

前言

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

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

一、FastDFS 与 golang 对接的代码

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

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

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

package mainimport (
"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 mainimport (
"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 不熟,仅供学习。

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,484
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,899
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,732
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,485
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,125
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,285