草庐IT

go - 为什么我会从此 API 调用中收到意外的 EOF?

coder 2023-07-01 原文

我有以下作为 AWS Lambda cron 运行的 Go 代码,但我不确定为什么会出现此错误:

sls logs --stage prod --region eu-west-1 --function esCronFn
2018/12/12 12:07:01 unexpected EOF
2018/12/12 12:07:01 unexpected EOF
END RequestId: 6bf33d28-fe03-11e8-949d-f39174c57cab
REPORT RequestId: 6bf33d28-fe03-11e8-949d-f39174c57cab  Duration: 464734.47 ms  Billed Duration: 464800 ms      Memory Size: 256 MB     Max Memory Used: 257 MB

RequestId: 6bf33d28-fe03-11e8-949d-f39174c57cab Process exited before completing request

这是我的 main.go - 它基本上连接到外部 API 并提取我正在处理并上传到 S3 存储桶的记录。

主要包

import (
    "bytes"
    "encoding/csv"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "net/url"
    "os"
    "strings"
    "time"

    "github.com/aws/aws-lambda-go/lambda"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-sdk-go/service/s3/s3iface"
)

var (
    // ENDPOINT is the endpoint from which incomplete CSV records are downloaded
    ENDPOINT = os.Getenv("ENDPOINT")

    PARSED_ENDPOINT *url.URL

    // TOKEN authenticates requests sent to eshot API
    TOKEN = os.Getenv("TOKEN")

    // BUCKET is the S3 bucket to which CSV files are uploaded
    BUCKET = os.Getenv("BUCKET")

    svc s3iface.S3API
)

// Record is the JSON response returned by a successful request to API
type EsRecord struct {
    Salutation   string    `json:"Salutation"`
    Firstname    string    `json:"Firstname"`
    Lastname     string    `json:"Lastname"`
    Company      string    `json:"Company"`
    EEA          string    `json:"EEA"`
    ModifiedDate time.Time `json:"ModifiedDate"`
    SubaccountID string    `json:"SubaccountId"`
    Email        string    `json:"Email"`
}

// CsvData holds reference to underlying buffer and the csv writer
type CsvData struct {
    Buffer *bytes.Buffer
    Writer *csv.Writer
}

func init() {
    today := time.Now()

    // If ENDPOINT is empty, It'll use this hardcoded endpoint. The ENDPOINT variable should not contain any text after "ModifiedDate gt". The actual date is currentDay-1
    if ENDPOINT == "" {
        ENDPOINT = "https://rest-api.domain.tld/Export/?$select=Email,Firstname,Lastname,SubaccountId,EEA,ModifiedDate&$filter=(EEA eq '' or EEA eq null) and ModifiedDate gt"
    }

    // Append CurrentDay-1 in YYYY-MM-DDTHH:MM:SSZ format.
    // The time is NOT in UTC. It's the local time of the machine on which lambda function was running
    ENDPOINT = fmt.Sprintf("%s %sT00:00:00Z", ENDPOINT, today.AddDate(0, 0, -1).Format("2006-01-02"))

    var err error
    PARSED_ENDPOINT, err = url.Parse(ENDPOINT)
    if err != nil {
        log.Fatalln("Invalid $ENDPOINT", err)
    }

    PARSED_ENDPOINT.RawQuery = QueryEscape(PARSED_ENDPOINT.RawQuery)
}

func main() {
    if TOKEN == "" {
        log.Fatalln("$TOKEN is empty")
    }
    if BUCKET == "" {
        log.Fatalln("$BUCKET is empty")
    }
    // Create S3 session
    svc = s3iface.S3API(s3.New(session.Must(session.NewSession())))

    lambda.Start(CreateAndUploadCsvToS3)
}

func CreateAndUploadCsvToS3() error {

    resp, err := fetchRecords()
    if err != nil {
        return fmt.Errorf("error in fetching records: %s", err)
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        b, _ := ioutil.ReadAll(resp.Body)
        return fmt.Errorf("api returned non 200 response(%d), URL: %s, %s", resp.StatusCode, PARSED_ENDPOINT.String(), string(b))
    }

    // API returns array of EshotRecord
    esRecords := []EsRecord{}

    err = json.NewDecoder(resp.Body).Decode(&esRecords)
    if err != nil {
        b, _ := ioutil.ReadAll(resp.Body)
        return fmt.Errorf("error in parsing response %s: %s", err, string(b))
    }

    recordsMap := ParseEsRecordsJSON(esRecords)

    ct := time.Now().String()
    for k, v := range recordsMap {

        key := fmt.Sprintf("%s_%s.csv", k, ct)

        _, err := svc.PutObject(&s3.PutObjectInput{
            Bucket: aws.String(BUCKET),
            // Key is in format, <subaccountid>_<current timestamp>.csv
            Key:  aws.String(key),
            Body: bytes.NewReader(v.Buffer.Bytes()),
        })
        if err != nil {
            return fmt.Errorf("error in uploading %s: %s", key, err)
        }
    }

    return nil
}

// ParseEsRecordsJSON takes an array of EsRecord
// Seperates each record by subAccountId
// Creates CSV files for each SubAccountId
// Returns the hashmap
func ParseEsRecordsJSON(esRecords []EsRecord) map[string]CsvData {
    recordsMap := make(map[string]CsvData)

    for _, v := range esRecords {
        // If v.SubaccountID was encountered for the first time
        // 1. Create a Buffer
        // 2. Write CSV headers to this buffer
        // 3. Store reference to this buffer and csv writer in hashmap
        if _, ok := recordsMap[v.SubaccountID]; !ok {
            var buf bytes.Buffer

            writer := csv.NewWriter(&buf)
            // Write CSV headers
            err := writer.Write([]string{"Firstname", "Lastname", "Email"})
            if err != nil {
                log.Printf("error occurred in inserting headers for subAccountId(%s): %s\n", v.SubaccountID, err)
            }

            // store reference to writer object for this subaccountid in hashmap
            recordsMap[v.SubaccountID] = CsvData{
                Buffer: &buf,
                Writer: writer,
            }
        }
        csvRef := recordsMap[v.SubaccountID]

        err := csvRef.Writer.Write([]string{v.Firstname, v.Lastname, v.Email})
        if err != nil {
            log.Printf("error occurred in inserting headers for subAccountId(%s): %s\n", v.SubaccountID, err)
        }
        csvRef.Writer.Flush()
    }
    return recordsMap
}

// FetchRecords makes a request to API and returns http.Response
func fetchRecords() (*http.Response, error) {
    req, err := http.NewRequest("GET", PARSED_ENDPOINT.String(), nil)
    if err != nil {
        return nil, err
    }

    req.Header.Set("Authorization", fmt.Sprintf("Token %s", TOKEN))
    client := &http.Client{}
    return client.Do(req)
}

// QueryEscape replaces URL unsafe characters as listed in HTTP RFC with their HEX values.
// The QueryEscape function in Go strictly adheres to the RFC and replaces all the characters listed in RFC with their HEX values.
// Curl/Postman only encodes parameters on a strict "need" only bases. Presumably, the endpoint does not seems to be working with Go's encoded string.
// This code escapes all the charactes and then performs uses string replace to make the URL more like what CURL would have done.
func QueryEscape(s string) string {
    s = url.QueryEscape(s)

    s = strings.Replace(s, "%2C", ",", -1)
    s = strings.Replace(s, "%24", "$", -1)
    s = strings.Replace(s, "%3D", "=", -1)
    s = strings.Replace(s, "+", "%20", -1)
    s = strings.Replace(s, "%26", "&", -1)
    s = strings.Replace(s, "%3A", ":", -1)

    return s
}

如果我将 ENDPOINT 更改为:

ENDPOINT = "https://rest-api.domain.tld/Export/?$select=Email,Firstname,Lastname,SubaccountId,EEA,ModifiedDate&$filter=(EEA eq '' or EEA eq null) and ModifiedDate gt"

ENDPOINT = "https://rest-api.domain.tld/Export/?$select=Email,Firstname,Lastname,SubaccountId,EEA,ModifiedDate&$filter=EEA eq '' and ModifiedDate gt"

我没有得到 EOF 错误,但是我没有得到完整的列表,运行 curl,我得到了我需要的数据,所以我不确定为什么我的代码失败了,如何最好地跟踪失败的地方?

最佳答案

问题是我的 lambda 函数只有 128Mb 内存,端点提供 130Mb 文件,所以增加这个值解决了这个问题

关于go - 为什么我会从此 API 调用中收到意外的 EOF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53747368/

有关go - 为什么我会从此 API 调用中收到意外的 EOF?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  3. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  6. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  7. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  8. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  9. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  10. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

随机推荐