内容简介:前言工作需要,第一次使用 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 不熟,仅供学习。
文件上传中转,如果是较大的文件,则采用将数据分片传输的方式进行。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Redis 集群分布式锁与 API 网关分布式限流
- 开源 | GateKeeper:滴滴开源的使用 Go 编写的不依赖分布式数据库的 API 网关
- Soul 网关发布 2.2.0,让高性能网关变得如此简单!
- 远行API网关(200428)
- zuul网关实现解析
- 设计一个HTTP网关
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Real-Time Collision Detection
Christer Ericson / CRC Press / 2004-12-22 / USD 98.95
Written by an expert in the game industry, Christer Ericson's new book is a comprehensive guide to the components of efficient real-time collision detection systems. The book provides the tools and kn......一起来看看 《Real-Time Collision Detection》 这本书的介绍吧!