Created
June 10, 2017 07:46
-
-
Save odeke-em/7cb79eb2dbd725c483ee087803f98a3d to your computer and use it in GitHub Desktop.
Server to receive, verify and process webhooks from Uber
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"log" | |
"net/http" | |
"golang.org/x/crypto/acme/autocert" | |
"github.com/orijtech/otils" | |
"github.com/orijtech/uber/uberhook" | |
) | |
func main() { | |
var http1 bool | |
var http1Port int | |
flag.BoolVar(&http1, "http1", false, "run the server as an HTTP1 server: useful for local dev") | |
flag.IntVar(&http1Port, "port", 8888, "the port to run the HTTP1 server on") | |
flag.Parse() | |
webhook, err := uberhook.New() | |
if err != nil { | |
log.Fatal(err) | |
} | |
mux := http.NewServeMux() | |
mux.Handle("/", webhook.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
defer r.Body.Close() | |
event, err := uberhook.FparseEvent(r.Body) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
log.Printf("Got an event from Uber: %#v\n", event) | |
fmt.Fprintf(w, "Successfully retrieved event!\n") | |
}))) | |
if http1 { | |
addr := fmt.Sprintf(":%d", http1Port) | |
log.Printf("Running as an http1 server on: %s\n", addr) | |
if err := http.ListenAndServe(addr, mux); err != nil { | |
log.Fatal(err) | |
} | |
return | |
} | |
log.Printf("Running as an http2 server!") | |
go func() { | |
nonHTTPSHandler := otils.RedirectAllTrafficTo("https://uberhook.example.com") | |
if err := http.ListenAndServe(":80", nonHTTPSHandler); err != nil { | |
log.Fatal(err) | |
} | |
}() | |
domains := []string{ | |
"uberhook.example.com", | |
"www.uberhook.example.com", | |
} | |
log.Fatal(http.Serve(autocert.NewListener(domains...), mux)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment