Upgrade to Pro — share decks privately, control downloads, hide ads and more …

AWS Lambda + Go

AWS Lambda + Go

AWS LambdaでGoを使うに当たっての基本的なことの紹介

Kentaro Kawano

June 16, 2017
Tweet

More Decks by Kentaro Kawano

Other Decks in Programming

Transcript

  1. ࣗݾ঺հ • Տ໺ ݈ଠ࿕ • γφδʔϚʔέςΟϯά(ג) ϓϩμΫτ։ൃ෦ ॴଐ • Synergy!

    ͷϚϧννϟωϧରԠ͕ओۀ຿ • ΞϓϦϓογϡج൫ߏங • GoͰߏங → ܰྔԽ͍ͨ͠ • LINE ϝοηʔδϯάج൫ߏங • callback෦෼ΛGoͰ
  2. AWS Lambda ͱ͸ • Function as a Service • AWSͷαʔϏε্ͷΠϕϯτʹରԠ

    • ྫ) S3ʹը૾͕Ξοϓϩʔυ͞Εͨͱ͖ɺϦαΠ ζ͢Δ • Node.jsɺJavaɺC#ɺPython͕αϙʔτ͞Ε͍ͯΔ • Lambda Function ͱ͍͏୯ҐͰ؅ཧ
  3. Lambda FunctionͷྫʢNode.jsʣ exports.handler = (event, context, callback) => { //

    Do Something callback(null, 'Hello from Lambda'); }; // event: Πϕϯτ৘ใ
 // context: ϥϯλΠϜ৘ใ
 // callback: ݺͼग़͠ݩʹ৘ใΛฦͨ͢Ίͷؔ਺
  4. Apex ͱ͸ • Lambda FunctionΛ؅ཧ͢Δπʔϧ • ެࣜҎ֎ͷݴޠ΋αϙʔτ • Functionͷ࣮૷ʹ࢖͑ΔϥΠϒϥϦ΋ఏڙ •

    ࣮૷ɺϏϧυɺσϓϩΠΛҰ؏ͯ͠ߦ͑Δ • Node.jsͷhandler + GoͷόΠφϦΛಉࠝͯ͠σϓϩ Π
  5. Apex جຊίϚϯυ # ϓϩδΣΫτॳظԽ(IAM role, policyͷ࡞੒) $ apex init #

    ϏϧυͷΈ $ apex build > hello.zip # ϏϧυɺσϓϩΠΛ࣮ߦ $ apex deploy # functionͷϦετʢAWS্ͷ৘ใ΋֬ೝͰ͖Δʣ $ apex list
  6. Apex ϑΝΠϧߏ੒ . ├ ─ ─ functions │ ├ ─

    ─ bot # σΟϨΫτϦ୯ҐͰ؅ཧ │ ├ ─ ─ function.json # function͝ͱͷઃఆ │ └ ─ ─ main.go ├ ─ ─ .apexignore # ແࢹ͢ΔϑΝΠϧͷઃఆ └ ─ ─ project.json # ϓϩδΣΫτશମͷઃఆ
  7. project.json { "name": "line-kensho", "description": "lineͷݕূ༻", "memory": 128, "timeout": 5,

    "role": "arn:aws:iam::...", "environment": {}, "runtime": "golang" }
  8. Lambda Function ͷྫʢApex+Goʣ import "github.com/apex/go-apex" func main() { apex.HandleFunc( func(e

    json.RawMessage, c *apex.Context) (interface{}, error) { return "Hello from Lambda", nil }) } // json.RawMessage: Πϕϯτ৘ใ // apex.Context: ϥϯλΠϜ৘ใ // return஋: ݺͼग़͠ݩʹฦ͢৘ใ
  9. API Gatewayͱ࿈ܞޙͷ࣮૷ type Request struct { Body string `json:"body"` Headers

    map[string]string `json:"headers"` HTTPMethod string `json:"httpMethod"` Path string `json:"path"` PathParameters map[string]string `json:"pathParameters"` QueryStringParameters map[string]string `json:"queryStringParameters”` // ...ଞ͍Ζ͍Ζ... } func main() { apex.HandleFunc( func(e json.RawMessage, c *apex.Context) (interface{}, error) { // ͜͜ͰϦΫΤετͷ৘ใΛ json.UnmarshalͳͲ͢Δඞཁ͕͋Δ => πϥΠ }) }
  10. ridgeͰͷ࣮૷ import "github.com/fujiwara/ridge" func main() { var mux = http.NewServeMux()

    mux.HandleFunc("/", handleRoot) ridge.Run(":8080", "/api", mux) } func handleHello(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") fmt.Fprintf(w, "Hello %s\n", r.FormValue("name")) } // ͍ͭ΋Ͳ͓Γͷ࣮૷ͰΒͪ͘Μ