首页 > 解决方案 > 如何从 Go 中的 Thrift Server 获取客户端 IP,thrift 版本 0.10.0?

问题描述

我正在用 Golang 编写一个节俭服务,我想了解如何在处理程序函数实现中获取客户端的 IP 地址。

我在Java中试过了,可以通过overwrite TProcessor#process(in,out)来获得,但是在Golang中似乎这种方式行不通。

serverTransport, err := thrift.NewTServerSocket(net.JoinHostPort(ip, strconv.FormatInt(port, 10)))
    //serverTransport, err := thrift.NewTServerSocket(net.JoinHostPort("127.0.0.1", "9999"))
    if err != nil {
        log.Error(err.Error())
        os.Exit(1)
    }
    protocolFactory := thrift.NewTCompactProtocolFactory()
    transportFactory := thrift.NewTFramedTransportFactoryMaxLength(thrift.NewTTransportFactory(), 524288000) 

    processor := iface.NewNMPDataServiceProcessor(new(impl.NMPDataService))

    server := thrift.NewTSimpleServer4(processor, serverTransport, transportFactory, protocolFactory)
    server.Serve()

    defer server.Stop()

NMPDataService接口的Handler实现:</p>

package impl

import (
    "NMPService/Framework/logger"
    "NMPService/NmpService/thrift/iface"
    "NMPService/NmpService/utils"
    "syscall"
    "errors"
    "fmt"
    "io"
    "io/ioutil"
    "os"
    "path/filepath"
    "regexp"
    "strconv"
    "strings"
    "time"

    "github.com/yeka/zip"
)

var log = logger.GetBeeLogger()

// NMPDataService .
type NMPDataService struct {
}

const (
    // MaxDownloadFileLimit ...
    MaxDownloadFileLimit int64 = 15728640
    TempFolder string = "tmp"
)

// ExistsFolder method
// Parameters:
//  - Path
func (handler *NMPDataService) ExistsFolder(path string) (bool, error) {
    log.Info("Check exist folder, path: %s", path)
    if strings.Contains(path, "\\") {
        path = strings.ReplaceAll(path, "\\", "/")
    }
    fileInfo, err := os.Stat(path)
    if os.IsNotExist(err) {
        log.Error("folder %s not exist", path)
        return false, nil
    }

    if !fileInfo.IsDir() {
        msg := "the path is not folder."
        log.Error(msg)
        return false, NewRPCException(1, msg, errors.New(msg))
    }

    if err != nil {
        log.Error("Check exist folder error.")
        return false, NewRPCException(1, "Check exist folder error", err)
    }

    return true, nil
}

以上是我在服务器端的代码。我想从服务器获取客户端 IP 信息。

标签: gothrift

解决方案


推荐阅读