Go語言實現FastDFS分布式存儲系統WebAPI網關


前言

  工作需要,第一次使用 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 不熟,僅供學習。

文件上傳中轉,如果是較大的文件,則采用將數據分片傳輸的方式進行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM