package {{.File.Package}}_httptransport

{{$file := .File}}

import (
       "log"
	"net/http"
	"encoding/json"
	context "golang.org/x/net/context"

        pb "{{cat .GoPWD "/" .DestinationDir | nospace | clean}}/pb"
        gokit_endpoint "github.com/go-kit/kit/endpoint"
        httptransport "github.com/go-kit/kit/transport/http"
        endpoints "{{cat .GoPWD "/" .DestinationDir | nospace | clean}}/endpoints"
)

var _ = log.Printf
var _ = gokit_endpoint.Chain
var _ = httptransport.NewClient


{{range .Service.Method}}
	{{if and (not .ServerStreaming) (not .ClientStreaming)}}
		func Make{{.Name}}Handler(ctx context.Context, svc pb.{{$file.Package | title}}ServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server {
			return httptransport.NewServer(
				ctx,
				endpoint,
				decode{{.Name}}Request,
				encodeResponse,
				[]httptransport.ServerOption{}...,
			)
		}

		func decode{{.Name}}Request(ctx context.Context, r *http.Request) (interface{}, error) {
			var req pb.{{.InputType | splitArray "." | last}}
			if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
				return nil, err
			}
			return &req, nil
		}
	{{end}}
{{end}}

func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
	return json.NewEncoder(w).Encode(response)
}

func RegisterHandlers(ctx context.Context, svc pb.{{$file.Package | title}}ServiceServer, mux *http.ServeMux, endpoints endpoints.Endpoints) error {
	{{range .Service.Method}}
		{{if and (not .ServerStreaming) (not .ClientStreaming)}}
			log.Println("new HTTP endpoint: \"/{{.Name}}\" (service={{$file.Package | title}})")
			mux.Handle("/{{.Name}}", Make{{.Name}}Handler(ctx, svc, endpoints.{{.Name}}Endpoint))
		{{end}}
	{{end}}
	return nil
}
