Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
106 lines (94 sloc) 2.77 KB
package flights
import (
"fmt"
"net/http"
"path/filepath"
"strings"
"text/template"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"go.pedge.io/openflights"
"go.pedge.io/pkg/http"
"go.pedge.io/pkg/tmpl"
)
var (
funcMap = template.FuncMap{
"lowercase": strings.ToLower,
"uppercase": strings.ToUpper,
"gcmapsegments": joinSegmentsGCMap,
}
routeExamples = []string{
"vie ord mem",
"vie oRD Mem",
"VIE-FRA-ORD",
"vie - fra - sfo",
"vie yyz buf/jfk vie",
"VIE YYZ BOS / jfk vie",
"vie ord kmem / kjfk vie",
"vie ord mem / jfk vie / hnl ewr",
}
)
type handler struct {
pkgtmpl.Templater
client openflights.Client
etcDirPath string
}
func newHandler(client openflights.Client, etcDirPath string) *handler {
return &handler{
pkgtmpl.NewTemplater(filepath.Join(etcDirPath, "tmpl")).WithFuncs(funcMap),
client,
etcDirPath,
}
}
func (h *handler) indexGet(responseWriter http.ResponseWriter, request *http.Request) {
if err := h.Execute(responseWriter, "index.html", routeExamples); err != nil {
h.handleError(responseWriter, err)
}
}
func (h *handler) milesGet(responseWriter http.ResponseWriter, request *http.Request) {
route := pkghttp.QueryGet(request, "route")
minMiles, err := pkghttp.QueryGetUint32(request, "min_miles")
if err != nil {
h.handleError(responseWriter, err)
return
}
percentage, err := pkghttp.QueryGetUint32(request, "percentage")
if err != nil {
h.handleError(responseWriter, err)
return
}
if percentage == 0 {
percentage = 100
}
getMilesRequest := &openflights.GetMilesRequest{
Route: route,
MinMiles: minMiles,
Percentage: percentage,
}
getMilesResponse, err := h.client.GetMiles(getMilesRequest)
if err != nil {
// unknown airport code is the only thing it can be right now, but this is relying on implementation, fix
if grpc.Code(err) == codes.NotFound && grpc.ErrorDesc(err) != "" {
h.handleError(responseWriter, fmt.Errorf("openflights: unknown airport code: %s", grpc.ErrorDesc(err)))
} else {
h.handleError(responseWriter, err)
}
return
}
if err := h.Execute(responseWriter, "miles.html", getMilesResponse); err != nil {
h.handleError(responseWriter, err)
}
}
func (h *handler) handleError(responseWriter http.ResponseWriter, givenErr error) {
responseWriter.WriteHeader(http.StatusInternalServerError)
if err := h.Execute(responseWriter, "error.html", givenErr.Error()); err != nil {
fmt.Fprintln(responseWriter, err.Error())
}
}
func joinSegmentsGCMap(segments []*openflights.GetMilesResponse_Segment) string {
segmentStrings := make([]string, len(segments))
for i, segment := range segments {
segmentStrings[i] = fmt.Sprintf("%s-%s", segment.SourceAirportId, segment.DestinationAirportId)
}
return template.URLQueryEscaper(strings.Join(segmentStrings, "\r\n"))
}