ã¿ã¤ãã«é·ãã Lambdaã§Goãæ£å¼ãµãã¼ããããã®ãé¦ãé·ããã¦å¾ ã¡ã¤ã¤ãApex 㧠Go ãå®è¡ãã¦ãã¾ãã
å æ¥ãAPI Gatewayã§åãããã¹ã¦ã®ãªã¯ã¨ã¹ããLambdaã«ä¸¸æããããã¨ãã§ããããã«ãªãã¾ããã
ããã¾ã§ã¯API Gatewayã§ãã¡ãã¡ãããã³ã°å®ç¾©ãä½ãã®ãé¢åã§ããã¾ãã¡æ®éã®WebAPIçãªãã®ãLambdaã§ä½ãæ°ãããªãã£ãããã§ãããããã§è¡ããã®ã§ã¯â¦? ã¨æã£ã¦ãcatch all ããããªã¯ã¨ã¹ãã¨ã¬ã¹ãã³ã¹ã net/http.Request 㨠net/http.ResponseWriter ã§æ±ããããã«ãã ridge ã¨ããã©ã¤ãã©ãªãæ¸ãã¦ã¿ã¾ããã
Readmeãã®ã¾ã¾ã§ããã以ä¸ã®ãã㪠Go ã®ã³ã¼ãã API Gateway (ãããã·çµ±å)+ Lambda + Apex ã§åãã¾ãã
package main import ( "encoding/json" "fmt" "log" "net/http" "os" "github.com/apex/go-apex" "github.com/fujiwara/ridge" ) var mux = http.NewServeMux() func init() { mux.HandleFunc("/", handleRoot) mux.HandleFunc("/hello", handleHello) } func main() { if os.Getenv("APEX") == "" { // ãã¼ã«ã«ã§åããããå ´åã¯ãã£ã¡ log.Println("starting up with local httpd") log.Fatal(http.ListenAndServe(":8080", mux)) } // Lambdaã§åãå ´åã¯ãã£ã¡ apex.HandleFunc(func(event json.RawMessage, ctx *apex.Context) (interface{}, error) { r, err := ridge.NewRequest(event) if err != nil { log.Println(err) return nil, err } w := ridge.NewResponseWriter() mux.ServeHTTP(w, r) return w.Response(), nil }) } func handleHello(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") fmt.Fprintf(w, "Hello %s\n", r.FormValue("name")) } func handleRoot(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") fmt.Fprintln(w, "Hello World") fmt.Fprintln(w, r.URL) }
- å
¥åã® JSON ã
*net/http.Request
ã«å¤æãã¦ã¢ããªã±ã¼ã·ã§ã³ã«æ¸¡ã ridge.ResponseWriter
ã¯net/http.ResponseWriter
interfaceãæã£ã¦ããã®ã§ããã«å¯¾ãã¦ã¬ã¹ãã³ã¹ãæ¸ãè¾¼ã
ã¨ããã¨ãæ®éã« Lambda 㧠Go ã® webapp ããããã®ãåãã¾ãã
ã¦ã¼ã¶ã®æ¸ãã³ã¼ãã¯æ®éã® Go ã® webapp ã¨åæ§ func(http.ResponseWriter, *http.Request)
ã§è¡ããã®ã§ããã¼ã«ã«ã§ã¯ http ãç´æ¥ listen ãããµã¼ãã¨ãã¦åããã¤ã¤ãAPI Gateway + Lambda ã§ãåãã³ã¼ããåãããâ¦â¦ããã¯ããããã¦åã便å©ãªã®ã§ã¯ï¼
å¶éã¨ã
- URLå¼æ°ã«ååã®å¤ (
foo=1&foo=2
ã¿ãããªã®) ãããã¨ãå ¥åEventã®æç¹ã§ã²ã¨ã¤ã«ãªã£ã¦ãã¾ã - HTTPãªã¯ã¨ã¹ã/ã¬ã¹ãã³ã¹ãããã§è¤æ°åããã®ããã£ã¦ãåæ§
- ãã¤ããªã®å ¥åºåãã§ããã®ãã©ããè¯ãåãããªã
ã¨ããç¾æç¹ã®å¶ç´ãããã¾ããã¡ããã¨ãã¤ããªãæ±ããã°ãç»åå¤æãµã¼ãã¿ãããªãã®ã«ã使ãã¦å¤¢ãåºããæããªã®ã§ããâ¦
ã¨ãããç¾æç¹ã§ããæ®éã«HTMLãJSONãè¿ãAPIãå®è£ ããã®ã«ã¯ä½¿ããã¯ãã§ãã®ã§ãæ¯éã試ããã ããã