apex / gateway Goto Github PK
View Code? Open in Web Editor NEWDrop-in replacement for Go net/http when running in AWS Lambda & API Gateway
License: MIT License
Drop-in replacement for Go net/http when running in AWS Lambda & API Gateway
License: MIT License
Hi,
I'm trying to get apex/gateway
to work, however the provided example doesn't really work:
apex ᐅ export GO111MODULE=on
apex ᐅ cat main.go
package main
import (
"fmt"
"log"
"net/http"
"github.com/apex/gateway"
"github.com/aws/aws-lambda-go"
)
func main() {
http.HandleFunc("/", hello)
log.Fatal(gateway.ListenAndServe(":3000", nil))
}
func hello(w http.ResponseWriter, r *http.Request) {
// example retrieving values from the api gateway proxy request context.
requestContext, ok := gateway.RequestContext(r.Context())
if !ok || requestContext.Authorizer["sub"] == nil {
fmt.Fprint(w, "Hello World from Go")
return
}
userID := requestContext.Authorizer["sub"].(string)
fmt.Fprintf(w, "Hello %s from Go", userID)
}
apex ᐅ go build main.go
go: finding github.com/aws/aws-lambda-go/events latest
go: finding github.com/aws/aws-lambda-go/lambda latest
build command-line-arguments: cannot load github.com/aws/aws-lambda-go: cannot find module providing package github.com/aws/aws-lambda-go
Any ideas? Thanks in advance.
BR,
Victor
Hello,
I've only just come across this library and I think it's great! I was trying to figure out how I could build some small generic tools that run directly on lambda for mostly house keeping tasks and I think this will do the trick.
I was wondering though, is it possible to use something like packr to include (a very small amount) of files within my go binary?
I've literally just done a drop in replacement for the gin app I was working on and it's deployed fine to lambda and serves my gin site but I was hoping to be able to include a couple of css, js files with this rather than hosting those in s3 or elsewhere.
When someone makes a GET request with encoded query parameters like
?phone=%2B919999999999
It is reencoded by the NewRequest function in the package to
?phone=%252B919999999999
which cannot be decoded back to the original +919999999999 resulting in issues with go's inbuilt r.URL.Query() and other functions.
I switched my API to use the cheaper HttpApi type from the REST protocol type https://s.natalian.org/2021-04-19/httpApi.txt which also has JWT Authorizer type support and now I get a redirect loop.
I guess it's something to do with the different interface PayloadFormatVersion 2.0?
This code works just fine.
package main
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/lambda"
)
func HandleRequest(ctx context.Context) (string, error) {
return fmt.Sprintf("Hello!"), nil
}
func main() {
lambda.Start(HandleRequest)
}
When I replace it with
package main
import (
"fmt"
"log"
"net/http"
"github.com/apex/gateway"
)
func main() {
http.HandleFunc("/", hello)
log.Fatal(gateway.ListenAndServe(":3000", nil))
// log.Fatal(http.ListenAndServe(":3000", nil))
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello!")
}
I am getting:
curl https://dqt4t5gx.execute-api.eu-central-1.amazonaws.com/
<a href="//dqt4t5gx.execute-api.eu-central-1.amazonaws.com/">Moved Permanently</a>.
Could this be because I am using the aws_apigatewayv2_api
resource?
Or any other pointers?
It would be nice if the library would sniff the content type if it's not already explicitly set rather than just using text/plain. I would be willing to work on this if you want.
go.mod need fix " github.com/aws/aws-lambda-go v1.17.0" to "github.com/aws/aws-lambda-go v1.32.0"
Request.URL
is set, but not Request.RequestURI
. This causes problems with certain logging middleware.
Using sam local start-api
is great but
I'd like to have a toggle to fall back to net/http
only:
ApexGatewayDisabled := os.Getenv("APEX_GATEWAY_DISABLED")
if ApexGatewayDisabled == "true" {
log.Fatal(http.ListenAndServe(":3000", nil))
} else {
log.Fatal(gateway.ListenAndServe(":3000", nil))
}
Everywhere AWS specific functionality is used above condition must also be checked.
Does this approach make sense or is there a better way?
Hello, i'm trying to migrate this Go project to lambda : https://github.com/readium/readium-lcp-server/tree/master/lcpserver
I found Apex/gateway, and it seems to be the solution. But i have few questions because my case is a bit complex and example provided doesnt help to understand how to correctly migrate.
The lcp server is divided in 3 parts:
lcpserver.go where main have the listenAndServe:
s := lcpserver.New(":"+parsedPort, readonly, &idx, &store, &lst, &cert, packager, authenticator)
if readonly {
log.Println("License server running in readonly mode on port " + parsedPort)
} else {
log.Println("License server running on port " + parsedPort)
}
log.Println("Using database " + dbURI)
log.Println("Public base URL=" + config.Config.LcpServer.PublicBaseUrl)
log.Println("License links:")
for nameOfLink, link := range config.Config.License.Links {
log.Println(" " + nameOfLink + " => " + link)
}
if err := s.ListenAndServe(); err != nil {
log.Println("Error " + err.Error())
```}
server.go in wich we have all redirection and the new above and all handlefunc:
func New(bindAddr string, readonly bool, idx *index.Index, st *storage.Store, lst *license.Store, cert *tls.Certificate, packager *pack.Packager, basicAuth *auth.BasicAuth) *Server {
sr := api.CreateServerRouter("")
s := &Server{
Server: http.Server{
Handler: sr.N,
Addr: bindAddr,
WriteTimeout: 240 * time.Second,
ReadTimeout: 5 * time.Second,
MaxHeaderBytes: 1 << 20,
},
readonly: readonly,
idx: idx,
st: st,
lst: lst,
cert: cert,
source: pack.ManualSource{},
}
// Route.PathPrefix: http://www.gorillatoolkit.org/pkg/mux#Route.PathPrefix
// Route.Subrouter: http://www.gorillatoolkit.org/pkg/mux#Route.Subrouter
// Router.StrictSlash: http://www.gorillatoolkit.org/pkg/mux#Router.StrictSlash
// methods related to EPUB encrypted content
contentRoutesPathPrefix := "/contents"
contentRoutes := sr.R.PathPrefix(contentRoutesPathPrefix).Subrouter().StrictSlash(false)
s.handleFunc(sr.R, contentRoutesPathPrefix, apilcp.ListContents).Methods("GET")
// get encrypted content by content id (a uuid)
s.handleFunc(contentRoutes, "/{content_id}", apilcp.GetContent).Methods("GET")
// get all licenses associated with a given content
s.handlePrivateFunc(contentRoutes, "/{content_id}/licenses", apilcp.ListLicensesForContent, basicAuth).Methods("GET")
if !readonly {
// put content to the storage
s.handlePrivateFunc(contentRoutes, "/{content_id}", apilcp.AddContent, basicAuth).Methods("PUT")
// generate a license for given content
s.handlePrivateFunc(contentRoutes, "/{content_id}/license", apilcp.GenerateLicense, basicAuth).Methods("POST")
// deprecated, from a typo in the lcp server spec
s.handlePrivateFunc(contentRoutes, "/{content_id}/licenses", apilcp.GenerateLicense, basicAuth).Methods("POST")
// generate a licensed publication
s.handlePrivateFunc(contentRoutes, "/{content_id}/publication", apilcp.GenerateLicensedPublication, basicAuth).Methods("POST")
// deprecated, from a typo in the lcp server spec
s.handlePrivateFunc(contentRoutes, "/{content_id}/publications", apilcp.GenerateLicensedPublication, basicAuth).Methods("POST")
}
// methods related to licenses
licenseRoutesPathPrefix := "/licenses"
licenseRoutes := sr.R.PathPrefix(licenseRoutesPathPrefix).Subrouter().StrictSlash(false)
s.handlePrivateFunc(sr.R, licenseRoutesPathPrefix, apilcp.ListLicenses, basicAuth).Methods("GET")
// get a license
s.handlePrivateFunc(licenseRoutes, "/{license_id}", apilcp.GetLicense, basicAuth).Methods("GET")
s.handlePrivateFunc(licenseRoutes, "/{license_id}", apilcp.GetLicense, basicAuth).Methods("POST")
// get a licensed publication via a license id
s.handlePrivateFunc(licenseRoutes, "/{license_id}/publication", apilcp.GetLicensedPublication, basicAuth).Methods("POST")
if !readonly {
// update a license
s.handlePrivateFunc(licenseRoutes, "/{license_id}", apilcp.UpdateLicense, basicAuth).Methods("PATCH")
}
s.source.Feed(packager.Incoming)
return s
}
and licence.go in which we have the apis, for example
// GenerateLicense generates and returns a new license,
// for a given content identified by its id
// plus a partial license given as input
func GenerateLicense(w http.ResponseWriter, r *http.Request, s Server) {
vars := mux.Vars(r)
// get the content id from the request URL
contentID := vars["content_id"]
log.Println("Generate License for content id", contentID)
// get the input body
// note: no need to create licIn / licOut here, as the input body contains
// info that we want to keep in the full license.
var lic license.License
err := DecodeJSONLicense(r, &lic)
if err != nil {
problem.Error(w, r, problem.Problem{Detail: err.Error()}, http.StatusBadRequest)
return
}
// check mandatory information in the input body
err = checkGenerateLicenseInput(&lic)
if err != nil {
problem.Error(w, r, problem.Problem{Detail: err.Error()}, http.StatusBadRequest)
return
}
// init the license with an id and issue date
license.Initialize(contentID, &lic)
// normalize the start and end date, UTC, no milliseconds
setRights(&lic)
// build the license
err = buildLicense(&lic, s)
if err != nil {
problem.Error(w, r, problem.Problem{Detail: err.Error()}, http.StatusInternalServerError)
return
}
// store the license in the db
err = s.Licenses().Add(lic)
if err != nil {
problem.Error(w, r, problem.Problem{Detail: err.Error()}, http.StatusInternalServerError)
//problem.Error(w, r, problem.Problem{Detail: err.Error(), Instance: contentID}, http.StatusInternalServerError)
return
}
// set http headers
w.Header().Add("Content-Type", api.ContentType_LCP_JSON)
w.Header().Add("Content-Disposition", `attachment; filename="license.lcpl"`)
w.WriteHeader(http.StatusCreated)
// send back the license
// do not escape characters
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
enc.Encode(lic)
// notify the lsd server of the creation of the license.
// this is an asynchronous call.
go notifyLsdServer(lic, s)
}
If i understand well how apex/gateway works, i have just to change `ListenAndServe()` in lcpserver.go and replace it by `gateway.ListenAndServe(":3000", nil)` ?
What about API gateway ? Should i create each ressource or use as posted in some examples on internet ?
Thanks for your answer
![image](https://user-images.githubusercontent.com/11942543/111508441-00771300-874c-11eb-97de-c8603725d023.png)
I'm looking around for a lambda adapter to use with go-chi/chi...Apex Gateway looks neat, but...unloved (trying to avoid calling this "abandoned").
I know one of the maintainers left $employer, but is this of interest to Apex to maintain, or maybe add some outside maintainers? Is there a popular fork of this, perhaps that I'm not aware of?
awslabs/aws-lambda-go-api-proxy is equally un-loved (including security vulns), davyzhang/agw is interesting but lacking stars. Is there some other well-maintained way that people are integrating lambda and go http routers?
With gateway a single Lambda function might handle many API Gateway requests, what happens when it exceeds the allocated memory?
It seems like AWS Lambda is somewhat flexible with the amount of memory the function may use, and I assume it will then start another if the account has concurrency available?
Ideally nothing out there should rely on query parameter ordering, but lots of things do unfortunately, so the request that is build and passed in to the handler should have the original rawquery set.
Hi @tj we're relying on RequestContext
, which is not yet in the 1.0 release. Can you tag current master as 1.1 or something? That way we can depend on an official release tag. Thanks!
I used this dependency in my go project for lambda function and api gateway. The api gateway do invoke the lambda function, however the api call returns 404 page not found error. And in the log, the path is /
instead of the /resource
. Do you have any suggestions?
Having JSON API as a Content Type header causes the response method to compress. It should return a string.
i had added follow sameple code, zip and upload to aws lambda
but its not work for me...
Any suggestion please?
import (
"fmt"
"log"
"net/http"
"os"
"github.com/apex/gateway"
)
func main() {
http.HandleFunc("/", hello)
log.Fatal(gateway.ListenAndServe(":3000", nil))
}
func hello(w http.ResponseWriter, r *http.Request) {
// example retrieving values from the api gateway proxy request context.
requestContext, ok := gateway.RequestContext(r.Context())
if !ok || requestContext.Authorizer["sub"] == nil {
fmt.Fprint(w, "Hello World from Go")
return
}
userID := requestContext.Authorizer["sub"].(string)
fmt.Fprintf(w, "Hello %s from Go", userID)
}
The golang http server will write out on close, just in case nothing was written. Could the End()
method be changed to call Write([]byte{})
so that it will trigger the headers and status OK being written?
This is using v2.0.0 of the library.
AWS added support for multiple-valued headers see here
We will be forking as this is urgent for us, but will probably submit a PR if our solution works.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.