Further consolidate the libraries
This commit is contained in:
7
api/.travis.yml
Normal file
7
api/.travis.yml
Normal file
@@ -0,0 +1,7 @@
|
||||
language: go
|
||||
go:
|
||||
- 1.10.x
|
||||
- 1.11.x
|
||||
notifications:
|
||||
slack:
|
||||
secure: T84DYmc4NzjYLgsRw69ckiIh1iOXKZmuB3HeRNo68/6DOvHa7ypNrSzYIOVS1n9iZmmGRk2pnDiqSBV4kqdEuQstb+T4SiqOgb9FGd7PsT2xKPg4WRRNECogeyZhxBmYilAK6IfcFI+XuLUW/i3KLdZMFfKzDE/EVHBHGueyE3aVWruUv7pLfONlOoxK44ok+Ixa5RIiVTaGmyJ3N3fjg0Css3MeC4mmwld+3zlSadWBql+Vl/K1+M9Zu2XTfreaqfLYqA2lvPorO5d7D/ZEWtxSOnSihnrlj4U0JL9sduAmCF4JndKSVvdbo0tPvdy1ODbOFUP+HFe10q0eDt39Jn2prpLr/ATAyGPWdC0DppHIQ1QNLNsjmn+F6/FIcWnO3zbPLUbMdDp9n9xg4GD2qb7vhmepd63rCMQCG6z+3WIYYDY3cgGxKKUeG+dvD2LtrsxfiXbq+o7vocwrtyrHAGZk4WEM7ZwMIzN/71qard3eD4P1OmbJwZPOOXQius50tVjN/aK1YV7X/uh0JTtwYyiL5H07IiYCGAfSPShouJ8JQBvNmGRUJwXcWLANK+sCIF9do0KsqxIkeJzcctSl2e+DP/EVRZXmxs24nP2bAdIyG+JBCuhED3vKyfLS8mR7P/LtrZL1vrbEZWRt3s8q5vhvWbcpwxGqo25GS1NDIjM=
|
18
api/README.md
Normal file
18
api/README.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Go API [](https://opensource.org/licenses/Apache-2.0) [](https://godoc.org/github.com/micro/go-micro/api) [](https://travis-ci.org/micro/go-micro/api) [](https://goreportcard.com/report/github.com/micro/go-micro/api)
|
||||
|
||||
Go API is a pluggable API framework driven by service discovery to help build powerful public API gateways.
|
||||
|
||||
## Overview
|
||||
|
||||
The Go API library provides api gateway routing capabilities. A microservice architecture decouples application logic into
|
||||
separate service. An api gateway provides a single entry point to consolidate these services into a unified api. The
|
||||
Go API uses routes defined in service discovery metadata to generate routing rules and serve http requests.
|
||||
|
||||
<img src="https://micro.mu/docs/images/go-api.png?v=1" alt="Go API" />
|
||||
|
||||
Go API is the basis for the [micro api](https://micro.mu/docs/api.html).
|
||||
|
||||
## Getting Started
|
||||
|
||||
See the [docs](https://micro.mu/docs/go-api.html) to learn more
|
||||
|
144
api/api.go
Normal file
144
api/api.go
Normal file
@@ -0,0 +1,144 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/micro/go-micro/registry"
|
||||
"github.com/micro/go-micro/server"
|
||||
)
|
||||
|
||||
// Endpoint is a mapping between an RPC method and HTTP endpoint
|
||||
type Endpoint struct {
|
||||
// RPC Method e.g. Greeter.Hello
|
||||
Name string
|
||||
// Description e.g what's this endpoint for
|
||||
Description string
|
||||
// API Handler e.g rpc, proxy
|
||||
Handler string
|
||||
// HTTP Host e.g example.com
|
||||
Host []string
|
||||
// HTTP Methods e.g GET, POST
|
||||
Method []string
|
||||
// HTTP Path e.g /greeter. Expect POSIX regex
|
||||
Path []string
|
||||
}
|
||||
|
||||
// Service represents an API service
|
||||
type Service struct {
|
||||
// Name of service
|
||||
Name string
|
||||
// The endpoint for this service
|
||||
Endpoint *Endpoint
|
||||
// Versions of this service
|
||||
Services []*registry.Service
|
||||
}
|
||||
|
||||
func strip(s string) string {
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func slice(s string) []string {
|
||||
var sl []string
|
||||
|
||||
for _, p := range strings.Split(s, ",") {
|
||||
if str := strip(p); len(str) > 0 {
|
||||
sl = append(sl, strip(p))
|
||||
}
|
||||
}
|
||||
|
||||
return sl
|
||||
}
|
||||
|
||||
// Encode encodes an endpoint to endpoint metadata
|
||||
func Encode(e *Endpoint) map[string]string {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return map[string]string{
|
||||
"endpoint": e.Name,
|
||||
"description": e.Description,
|
||||
"method": strings.Join(e.Method, ","),
|
||||
"path": strings.Join(e.Path, ","),
|
||||
"host": strings.Join(e.Host, ","),
|
||||
"handler": e.Handler,
|
||||
}
|
||||
}
|
||||
|
||||
// Decode decodes endpoint metadata into an endpoint
|
||||
func Decode(e map[string]string) *Endpoint {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &Endpoint{
|
||||
Name: e["endpoint"],
|
||||
Description: e["description"],
|
||||
Method: slice(e["method"]),
|
||||
Path: slice(e["path"]),
|
||||
Host: slice(e["host"]),
|
||||
Handler: e["handler"],
|
||||
}
|
||||
}
|
||||
|
||||
// Validate validates an endpoint to guarantee it won't blow up when being served
|
||||
func Validate(e *Endpoint) error {
|
||||
if e == nil {
|
||||
return errors.New("endpoint is nil")
|
||||
}
|
||||
|
||||
if len(e.Name) == 0 {
|
||||
return errors.New("name required")
|
||||
}
|
||||
|
||||
for _, p := range e.Path {
|
||||
_, err := regexp.CompilePOSIX(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if len(e.Handler) == 0 {
|
||||
return errors.New("invalid handler")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/*
|
||||
Design ideas
|
||||
|
||||
// Gateway is an api gateway interface
|
||||
type Gateway interface {
|
||||
// Register a http handler
|
||||
Handle(pattern string, http.Handler)
|
||||
// Register a route
|
||||
RegisterRoute(r Route)
|
||||
// Init initialises the command line.
|
||||
// It also parses further options.
|
||||
Init(...Option) error
|
||||
// Run the gateway
|
||||
Run() error
|
||||
}
|
||||
|
||||
// NewGateway returns a new api gateway
|
||||
func NewGateway() Gateway {
|
||||
return newGateway()
|
||||
}
|
||||
*/
|
||||
|
||||
// WithEndpoint returns a server.HandlerOption with endpoint metadata set
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// proto.RegisterHandler(service.Server(), new(Handler), api.WithEndpoint(
|
||||
// &api.Endpoint{
|
||||
// Name: "Greeter.Hello",
|
||||
// Path: []string{"/greeter"},
|
||||
// },
|
||||
// ))
|
||||
func WithEndpoint(e *Endpoint) server.HandlerOption {
|
||||
return server.EndpointMetadata(e.Name, Encode(e))
|
||||
}
|
113
api/api_test.go
Normal file
113
api/api_test.go
Normal file
@@ -0,0 +1,113 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEncoding(t *testing.T) {
|
||||
testData := []*Endpoint{
|
||||
nil,
|
||||
{
|
||||
Name: "Foo.Bar",
|
||||
Description: "A test endpoint",
|
||||
Handler: "meta",
|
||||
Host: []string{"foo.com"},
|
||||
Method: []string{"GET"},
|
||||
Path: []string{"/test"},
|
||||
},
|
||||
}
|
||||
|
||||
compare := func(expect, got []string) bool {
|
||||
// no data to compare, return true
|
||||
if len(expect) == 0 && len(got) == 0 {
|
||||
return true
|
||||
}
|
||||
// no data expected but got some return false
|
||||
if len(expect) == 0 && len(got) > 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
// compare expected with what we got
|
||||
for _, e := range expect {
|
||||
var seen bool
|
||||
for _, g := range got {
|
||||
if e == g {
|
||||
seen = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !seen {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// we're done, return true
|
||||
return true
|
||||
}
|
||||
|
||||
for _, d := range testData {
|
||||
// encode
|
||||
e := Encode(d)
|
||||
// decode
|
||||
de := Decode(e)
|
||||
|
||||
// nil endpoint returns nil
|
||||
if d == nil {
|
||||
if e != nil {
|
||||
t.Fatalf("expected nil got %v", e)
|
||||
}
|
||||
if de != nil {
|
||||
t.Fatalf("expected nil got %v", de)
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// check encoded map
|
||||
name := e["endpoint"]
|
||||
desc := e["description"]
|
||||
method := strings.Split(e["method"], ",")
|
||||
path := strings.Split(e["path"], ",")
|
||||
host := strings.Split(e["host"], ",")
|
||||
handler := e["handler"]
|
||||
|
||||
if name != d.Name {
|
||||
t.Fatalf("expected %v got %v", d.Name, name)
|
||||
}
|
||||
if desc != d.Description {
|
||||
t.Fatalf("expected %v got %v", d.Description, desc)
|
||||
}
|
||||
if handler != d.Handler {
|
||||
t.Fatalf("expected %v got %v", d.Handler, handler)
|
||||
}
|
||||
if ok := compare(d.Method, method); !ok {
|
||||
t.Fatalf("expected %v got %v", d.Method, method)
|
||||
}
|
||||
if ok := compare(d.Path, path); !ok {
|
||||
t.Fatalf("expected %v got %v", d.Path, path)
|
||||
}
|
||||
if ok := compare(d.Host, host); !ok {
|
||||
t.Fatalf("expected %v got %v", d.Host, host)
|
||||
}
|
||||
|
||||
if de.Name != d.Name {
|
||||
t.Fatalf("expected %v got %v", d.Name, de.Name)
|
||||
}
|
||||
if de.Description != d.Description {
|
||||
t.Fatalf("expected %v got %v", d.Description, de.Description)
|
||||
}
|
||||
if de.Handler != d.Handler {
|
||||
t.Fatalf("expected %v got %v", d.Handler, de.Handler)
|
||||
}
|
||||
if ok := compare(d.Method, de.Method); !ok {
|
||||
t.Fatalf("expected %v got %v", d.Method, de.Method)
|
||||
}
|
||||
if ok := compare(d.Path, de.Path); !ok {
|
||||
t.Fatalf("expected %v got %v", d.Path, de.Path)
|
||||
}
|
||||
if ok := compare(d.Host, de.Host); !ok {
|
||||
t.Fatalf("expected %v got %v", d.Host, de.Host)
|
||||
}
|
||||
}
|
||||
}
|
117
api/handler/api/api.go
Normal file
117
api/handler/api/api.go
Normal file
@@ -0,0 +1,117 @@
|
||||
// Package api provides an http-rpc handler which provides the entire http request over rpc
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
goapi "github.com/micro/go-micro/api"
|
||||
"github.com/micro/go-micro/api/handler"
|
||||
"github.com/micro/go-micro/client"
|
||||
"github.com/micro/go-micro/errors"
|
||||
"github.com/micro/go-micro/selector"
|
||||
"github.com/micro/go-micro/util/ctx"
|
||||
api "github.com/micro/micro/api/proto"
|
||||
)
|
||||
|
||||
type apiHandler struct {
|
||||
opts handler.Options
|
||||
s *goapi.Service
|
||||
}
|
||||
|
||||
const (
|
||||
Handler = "api"
|
||||
)
|
||||
|
||||
// API handler is the default handler which takes api.Request and returns api.Response
|
||||
func (a *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
request, err := requestToProto(r)
|
||||
if err != nil {
|
||||
er := errors.InternalServerError("go.micro.api", err.Error())
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
w.Write([]byte(er.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
var service *goapi.Service
|
||||
|
||||
if a.s != nil {
|
||||
// we were given the service
|
||||
service = a.s
|
||||
} else if a.opts.Router != nil {
|
||||
// try get service from router
|
||||
s, err := a.opts.Router.Route(r)
|
||||
if err != nil {
|
||||
er := errors.InternalServerError("go.micro.api", err.Error())
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
w.Write([]byte(er.Error()))
|
||||
return
|
||||
}
|
||||
service = s
|
||||
} else {
|
||||
// we have no way of routing the request
|
||||
er := errors.InternalServerError("go.micro.api", "no route found")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(500)
|
||||
w.Write([]byte(er.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// create request and response
|
||||
c := a.opts.Service.Client()
|
||||
req := c.NewRequest(service.Name, service.Endpoint.Name, request)
|
||||
rsp := &api.Response{}
|
||||
|
||||
// create the context from headers
|
||||
cx := ctx.FromRequest(r)
|
||||
// create strategy
|
||||
so := selector.WithStrategy(strategy(service.Services))
|
||||
|
||||
if err := c.Call(cx, req, rsp, client.WithSelectOption(so)); err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
ce := errors.Parse(err.Error())
|
||||
switch ce.Code {
|
||||
case 0:
|
||||
w.WriteHeader(500)
|
||||
default:
|
||||
w.WriteHeader(int(ce.Code))
|
||||
}
|
||||
w.Write([]byte(ce.Error()))
|
||||
return
|
||||
} else if rsp.StatusCode == 0 {
|
||||
rsp.StatusCode = http.StatusOK
|
||||
}
|
||||
|
||||
for _, header := range rsp.GetHeader() {
|
||||
for _, val := range header.Values {
|
||||
w.Header().Add(header.Key, val)
|
||||
}
|
||||
}
|
||||
|
||||
if len(w.Header().Get("Content-Type")) == 0 {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
w.WriteHeader(int(rsp.StatusCode))
|
||||
w.Write([]byte(rsp.Body))
|
||||
}
|
||||
|
||||
func (a *apiHandler) String() string {
|
||||
return "api"
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
return &apiHandler{
|
||||
opts: options,
|
||||
}
|
||||
}
|
||||
|
||||
func WithService(s *goapi.Service, opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
return &apiHandler{
|
||||
opts: options,
|
||||
s: s,
|
||||
}
|
||||
}
|
107
api/handler/api/util.go
Normal file
107
api/handler/api/util.go
Normal file
@@ -0,0 +1,107 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/micro/go-micro/registry"
|
||||
"github.com/micro/go-micro/selector"
|
||||
api "github.com/micro/micro/api/proto"
|
||||
)
|
||||
|
||||
func requestToProto(r *http.Request) (*api.Request, error) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
return nil, fmt.Errorf("Error parsing form: %v", err)
|
||||
}
|
||||
|
||||
req := &api.Request{
|
||||
Path: r.URL.Path,
|
||||
Method: r.Method,
|
||||
Header: make(map[string]*api.Pair),
|
||||
Get: make(map[string]*api.Pair),
|
||||
Post: make(map[string]*api.Pair),
|
||||
Url: r.URL.String(),
|
||||
}
|
||||
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
ct = "application/x-www-form-urlencoded"
|
||||
r.Header.Set("Content-Type", ct)
|
||||
}
|
||||
|
||||
switch ct {
|
||||
case "application/x-www-form-urlencoded":
|
||||
// expect form vals
|
||||
default:
|
||||
data, _ := ioutil.ReadAll(r.Body)
|
||||
req.Body = string(data)
|
||||
}
|
||||
|
||||
// Set X-Forwarded-For if it does not exist
|
||||
if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||
if prior, ok := r.Header["X-Forwarded-For"]; ok {
|
||||
ip = strings.Join(prior, ", ") + ", " + ip
|
||||
}
|
||||
|
||||
// Set the header
|
||||
req.Header["X-Forwarded-For"] = &api.Pair{
|
||||
Key: "X-Forwarded-For",
|
||||
Values: []string{ip},
|
||||
}
|
||||
}
|
||||
|
||||
// Host is stripped from net/http Headers so let's add it
|
||||
req.Header["Host"] = &api.Pair{
|
||||
Key: "Host",
|
||||
Values: []string{r.Host},
|
||||
}
|
||||
|
||||
// Get data
|
||||
for key, vals := range r.URL.Query() {
|
||||
header, ok := req.Get[key]
|
||||
if !ok {
|
||||
header = &api.Pair{
|
||||
Key: key,
|
||||
}
|
||||
req.Get[key] = header
|
||||
}
|
||||
header.Values = vals
|
||||
}
|
||||
|
||||
// Post data
|
||||
for key, vals := range r.PostForm {
|
||||
header, ok := req.Post[key]
|
||||
if !ok {
|
||||
header = &api.Pair{
|
||||
Key: key,
|
||||
}
|
||||
req.Post[key] = header
|
||||
}
|
||||
header.Values = vals
|
||||
}
|
||||
|
||||
for key, vals := range r.Header {
|
||||
header, ok := req.Header[key]
|
||||
if !ok {
|
||||
header = &api.Pair{
|
||||
Key: key,
|
||||
}
|
||||
req.Header[key] = header
|
||||
}
|
||||
header.Values = vals
|
||||
}
|
||||
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// strategy is a hack for selection
|
||||
func strategy(services []*registry.Service) selector.Strategy {
|
||||
return func(_ []*registry.Service) selector.Next {
|
||||
// ignore input to this function, use services above
|
||||
return selector.Random(services)
|
||||
}
|
||||
}
|
46
api/handler/api/util_test.go
Normal file
46
api/handler/api/util_test.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRequestToProto(t *testing.T) {
|
||||
testData := []*http.Request{
|
||||
&http.Request{
|
||||
Method: "GET",
|
||||
Header: http.Header{
|
||||
"Header": []string{"test"},
|
||||
},
|
||||
URL: &url.URL{
|
||||
Scheme: "http",
|
||||
Host: "localhost",
|
||||
Path: "/foo/bar",
|
||||
RawQuery: "param1=value1",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range testData {
|
||||
p, err := requestToProto(d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Path != d.URL.Path {
|
||||
t.Fatalf("Expected path %s got %s", d.URL.Path, p.Path)
|
||||
}
|
||||
if p.Method != d.Method {
|
||||
t.Fatalf("Expected method %s got %s", d.Method, p.Method)
|
||||
}
|
||||
for k, v := range d.Header {
|
||||
if val, ok := p.Header[k]; !ok {
|
||||
t.Fatalf("Expected header %s", k)
|
||||
} else {
|
||||
if val.Values[0] != v[0] {
|
||||
t.Fatalf("Expected val %s, got %s", val.Values[0], v[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
268
api/handler/broker/broker.go
Normal file
268
api/handler/broker/broker.go
Normal file
@@ -0,0 +1,268 @@
|
||||
// Package broker provides a go-micro/broker handler
|
||||
package broker
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/micro/go-micro/api/handler"
|
||||
"github.com/micro/go-micro/broker"
|
||||
"github.com/micro/go-micro/util/log"
|
||||
)
|
||||
|
||||
const (
|
||||
Handler = "broker"
|
||||
|
||||
pingTime = (readDeadline * 9) / 10
|
||||
readLimit = 16384
|
||||
readDeadline = 60 * time.Second
|
||||
writeDeadline = 10 * time.Second
|
||||
)
|
||||
|
||||
type brokerHandler struct {
|
||||
opts handler.Options
|
||||
u websocket.Upgrader
|
||||
}
|
||||
|
||||
type conn struct {
|
||||
b broker.Broker
|
||||
cType string
|
||||
topic string
|
||||
queue string
|
||||
exit chan bool
|
||||
|
||||
sync.Mutex
|
||||
ws *websocket.Conn
|
||||
}
|
||||
|
||||
var (
|
||||
once sync.Once
|
||||
contentType = "text/plain"
|
||||
)
|
||||
|
||||
func checkOrigin(r *http.Request) bool {
|
||||
origin := r.Header["Origin"]
|
||||
if len(origin) == 0 {
|
||||
return true
|
||||
}
|
||||
u, err := url.Parse(origin[0])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return u.Host == r.Host
|
||||
}
|
||||
|
||||
func (c *conn) close() {
|
||||
select {
|
||||
case <-c.exit:
|
||||
return
|
||||
default:
|
||||
close(c.exit)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *conn) readLoop() {
|
||||
defer func() {
|
||||
c.close()
|
||||
c.ws.Close()
|
||||
}()
|
||||
|
||||
// set read limit/deadline
|
||||
c.ws.SetReadLimit(readLimit)
|
||||
c.ws.SetReadDeadline(time.Now().Add(readDeadline))
|
||||
|
||||
// set close handler
|
||||
ch := c.ws.CloseHandler()
|
||||
c.ws.SetCloseHandler(func(code int, text string) error {
|
||||
err := ch(code, text)
|
||||
c.close()
|
||||
return err
|
||||
})
|
||||
|
||||
// set pong handler
|
||||
c.ws.SetPongHandler(func(string) error {
|
||||
c.ws.SetReadDeadline(time.Now().Add(readDeadline))
|
||||
return nil
|
||||
})
|
||||
|
||||
for {
|
||||
_, message, err := c.ws.ReadMessage()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.b.Publish(c.topic, &broker.Message{
|
||||
Header: map[string]string{"Content-Type": c.cType},
|
||||
Body: message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (c *conn) write(mType int, data []byte) error {
|
||||
c.Lock()
|
||||
c.ws.SetWriteDeadline(time.Now().Add(writeDeadline))
|
||||
err := c.ws.WriteMessage(mType, data)
|
||||
c.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *conn) writeLoop() {
|
||||
ticker := time.NewTicker(pingTime)
|
||||
|
||||
var opts []broker.SubscribeOption
|
||||
|
||||
if len(c.queue) > 0 {
|
||||
opts = append(opts, broker.Queue(c.queue))
|
||||
}
|
||||
|
||||
subscriber, err := c.b.Subscribe(c.topic, func(p broker.Publication) error {
|
||||
b, err := json.Marshal(p.Message())
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return c.write(websocket.TextMessage, b)
|
||||
}, opts...)
|
||||
|
||||
defer func() {
|
||||
subscriber.Unsubscribe()
|
||||
ticker.Stop()
|
||||
c.ws.Close()
|
||||
}()
|
||||
|
||||
if err != nil {
|
||||
log.Log(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if err := c.write(websocket.PingMessage, []byte{}); err != nil {
|
||||
return
|
||||
}
|
||||
case <-c.exit:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *brokerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
br := b.opts.Service.Client().Options().Broker
|
||||
|
||||
// Setup the broker
|
||||
once.Do(func() {
|
||||
br.Init()
|
||||
br.Connect()
|
||||
})
|
||||
|
||||
// Parse
|
||||
r.ParseForm()
|
||||
topic := r.Form.Get("topic")
|
||||
|
||||
// Can't do anything without a topic
|
||||
if len(topic) == 0 {
|
||||
http.Error(w, "Topic not specified", 400)
|
||||
return
|
||||
}
|
||||
|
||||
// Post assumed to be Publish
|
||||
if r.Method == "POST" {
|
||||
// Create a broker message
|
||||
msg := &broker.Message{
|
||||
Header: make(map[string]string),
|
||||
}
|
||||
|
||||
// Set header
|
||||
for k, v := range r.Header {
|
||||
msg.Header[k] = strings.Join(v, ", ")
|
||||
}
|
||||
|
||||
// Read body
|
||||
b, err := ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
|
||||
// Set body
|
||||
msg.Body = b
|
||||
|
||||
// Publish
|
||||
br.Publish(topic, msg)
|
||||
return
|
||||
}
|
||||
|
||||
// now back to our regularly scheduled programming
|
||||
|
||||
if r.Method != "GET" {
|
||||
http.Error(w, "Method not allowed", 405)
|
||||
return
|
||||
}
|
||||
|
||||
queue := r.Form.Get("queue")
|
||||
|
||||
ws, err := b.u.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Log(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
cType := r.Header.Get("Content-Type")
|
||||
if len(cType) == 0 {
|
||||
cType = contentType
|
||||
}
|
||||
|
||||
c := &conn{
|
||||
b: br,
|
||||
cType: cType,
|
||||
topic: topic,
|
||||
queue: queue,
|
||||
exit: make(chan bool),
|
||||
ws: ws,
|
||||
}
|
||||
|
||||
go c.writeLoop()
|
||||
c.readLoop()
|
||||
}
|
||||
|
||||
func (b *brokerHandler) String() string {
|
||||
return "broker"
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
return &brokerHandler{
|
||||
u: websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true
|
||||
},
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
},
|
||||
opts: handler.NewOptions(opts...),
|
||||
}
|
||||
}
|
||||
|
||||
func WithCors(cors map[string]bool, opts ...handler.Option) handler.Handler {
|
||||
return &brokerHandler{
|
||||
u: websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
if origin := r.Header.Get("Origin"); cors[origin] {
|
||||
return true
|
||||
} else if len(origin) > 0 && cors["*"] {
|
||||
return true
|
||||
} else if checkOrigin(r) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
},
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
},
|
||||
opts: handler.NewOptions(opts...),
|
||||
}
|
||||
}
|
94
api/handler/cloudevents/cloudevents.go
Normal file
94
api/handler/cloudevents/cloudevents.go
Normal file
@@ -0,0 +1,94 @@
|
||||
// Package cloudevents provides a cloudevents handler publishing the event using the go-micro/client
|
||||
package cloudevents
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/micro/go-micro/api/handler"
|
||||
"github.com/micro/go-micro/util/ctx"
|
||||
)
|
||||
|
||||
type event struct {
|
||||
options handler.Options
|
||||
}
|
||||
|
||||
var (
|
||||
Handler = "cloudevents"
|
||||
versionRe = regexp.MustCompilePOSIX("^v[0-9]+$")
|
||||
)
|
||||
|
||||
func eventName(parts []string) string {
|
||||
return strings.Join(parts, ".")
|
||||
}
|
||||
|
||||
func evRoute(ns, p string) (string, string) {
|
||||
p = path.Clean(p)
|
||||
p = strings.TrimPrefix(p, "/")
|
||||
|
||||
if len(p) == 0 {
|
||||
return ns, "event"
|
||||
}
|
||||
|
||||
parts := strings.Split(p, "/")
|
||||
|
||||
// no path
|
||||
if len(parts) == 0 {
|
||||
// topic: namespace
|
||||
// action: event
|
||||
return strings.Trim(ns, "."), "event"
|
||||
}
|
||||
|
||||
// Treat /v[0-9]+ as versioning
|
||||
// /v1/foo/bar => topic: v1.foo action: bar
|
||||
if len(parts) >= 2 && versionRe.Match([]byte(parts[0])) {
|
||||
topic := ns + "." + strings.Join(parts[:2], ".")
|
||||
action := eventName(parts[1:])
|
||||
return topic, action
|
||||
}
|
||||
|
||||
// /foo => topic: ns.foo action: foo
|
||||
// /foo/bar => topic: ns.foo action: bar
|
||||
topic := ns + "." + strings.Join(parts[:1], ".")
|
||||
action := eventName(parts[1:])
|
||||
|
||||
return topic, action
|
||||
}
|
||||
|
||||
func (e *event) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// request to topic:event
|
||||
// create event
|
||||
// publish to topic
|
||||
topic, _ := evRoute(e.options.Namespace, r.URL.Path)
|
||||
|
||||
// create event
|
||||
ev, err := FromRequest(r)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
|
||||
// get client
|
||||
c := e.options.Service.Client()
|
||||
|
||||
// create publication
|
||||
p := c.NewMessage(topic, ev)
|
||||
|
||||
// publish event
|
||||
if err := c.Publish(ctx.FromRequest(r), p); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (e *event) String() string {
|
||||
return "cloudevents"
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
return &event{
|
||||
options: handler.NewOptions(opts...),
|
||||
}
|
||||
}
|
282
api/handler/cloudevents/event.go
Normal file
282
api/handler/cloudevents/event.go
Normal file
@@ -0,0 +1,282 @@
|
||||
/*
|
||||
* From: https://github.com/serverless/event-gateway/blob/master/event/event.go
|
||||
* Modified: Strip to handler requirements
|
||||
*
|
||||
* Copyright 2017 Serverless, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
*/
|
||||
|
||||
package cloudevents
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/pborman/uuid"
|
||||
"gopkg.in/go-playground/validator.v9"
|
||||
)
|
||||
|
||||
const (
|
||||
// TransformationVersion is indicative of the revision of how Event Gateway transforms a request into CloudEvents format.
|
||||
TransformationVersion = "0.1"
|
||||
|
||||
// CloudEventsVersion currently supported by Event Gateway
|
||||
CloudEventsVersion = "0.1"
|
||||
)
|
||||
|
||||
// Event is a default event structure. All data that passes through the Event Gateway
|
||||
// is formatted to a format defined CloudEvents v0.1 spec.
|
||||
type Event struct {
|
||||
EventType string `json:"eventType" validate:"required"`
|
||||
EventTypeVersion string `json:"eventTypeVersion,omitempty"`
|
||||
CloudEventsVersion string `json:"cloudEventsVersion" validate:"required"`
|
||||
Source string `json:"source" validate:"uri,required"`
|
||||
EventID string `json:"eventID" validate:"required"`
|
||||
EventTime *time.Time `json:"eventTime,omitempty"`
|
||||
SchemaURL string `json:"schemaURL,omitempty"`
|
||||
Extensions map[string]interface{} `json:"extensions,omitempty"`
|
||||
ContentType string `json:"contentType,omitempty"`
|
||||
Data interface{} `json:"data"`
|
||||
}
|
||||
|
||||
// New return new instance of Event.
|
||||
func New(eventType string, mimeType string, payload interface{}) *Event {
|
||||
now := time.Now()
|
||||
|
||||
event := &Event{
|
||||
EventType: eventType,
|
||||
CloudEventsVersion: CloudEventsVersion,
|
||||
Source: "https://micro.mu",
|
||||
EventID: uuid.NewUUID().String(),
|
||||
EventTime: &now,
|
||||
ContentType: mimeType,
|
||||
Data: payload,
|
||||
Extensions: map[string]interface{}{
|
||||
"eventgateway": map[string]interface{}{
|
||||
"transformed": "true",
|
||||
"transformation-version": TransformationVersion,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
event.Data = normalizePayload(event.Data, event.ContentType)
|
||||
return event
|
||||
}
|
||||
|
||||
// FromRequest takes an HTTP request and returns an Event along with path. Most of the implementation
|
||||
// is based on https://github.com/cloudevents/spec/blob/master/http-transport-binding.md.
|
||||
// This function also supports legacy mode where event type is sent in Event header.
|
||||
func FromRequest(r *http.Request) (*Event, error) {
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
mimeType, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
if err.Error() != "mime: no media type" {
|
||||
return nil, err
|
||||
}
|
||||
mimeType = "application/octet-stream"
|
||||
}
|
||||
// Read request body
|
||||
body := []byte{}
|
||||
if r.Body != nil {
|
||||
body, err = ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
var event *Event
|
||||
if mimeType == mimeCloudEventsJSON { // CloudEvents Structured Content Mode
|
||||
return parseAsCloudEvent(mimeType, body)
|
||||
} else if isCloudEventsBinaryContentMode(r.Header) { // CloudEvents Binary Content Mode
|
||||
return parseAsCloudEventBinary(r.Header, body)
|
||||
} else if isLegacyMode(r.Header) {
|
||||
if mimeType == mimeJSON { // CloudEvent in Legacy Mode
|
||||
event, err = parseAsCloudEvent(mimeType, body)
|
||||
if err != nil {
|
||||
return New(string(r.Header.Get("event")), mimeType, body), nil
|
||||
}
|
||||
return event, err
|
||||
}
|
||||
|
||||
return New(string(r.Header.Get("event")), mimeType, body), nil
|
||||
}
|
||||
|
||||
return New("http.request", mimeJSON, newHTTPRequestData(r, body)), nil
|
||||
}
|
||||
|
||||
// Validate Event struct
|
||||
func (e *Event) Validate() error {
|
||||
validate := validator.New()
|
||||
err := validate.Struct(e)
|
||||
if err != nil {
|
||||
return fmt.Errorf("CloudEvent not valid: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isLegacyMode(headers http.Header) bool {
|
||||
if headers.Get("Event") != "" {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func isCloudEventsBinaryContentMode(headers http.Header) bool {
|
||||
if headers.Get("CE-EventType") != "" &&
|
||||
headers.Get("CE-CloudEventsVersion") != "" &&
|
||||
headers.Get("CE-Source") != "" &&
|
||||
headers.Get("CE-EventID") != "" {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func parseAsCloudEventBinary(headers http.Header, payload interface{}) (*Event, error) {
|
||||
event := &Event{
|
||||
EventType: headers.Get("CE-EventType"),
|
||||
EventTypeVersion: headers.Get("CE-EventTypeVersion"),
|
||||
CloudEventsVersion: headers.Get("CE-CloudEventsVersion"),
|
||||
Source: headers.Get("CE-Source"),
|
||||
EventID: headers.Get("CE-EventID"),
|
||||
ContentType: headers.Get("Content-Type"),
|
||||
Data: payload,
|
||||
}
|
||||
|
||||
err := event.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if headers.Get("CE-EventTime") != "" {
|
||||
val, err := time.Parse(time.RFC3339, headers.Get("CE-EventTime"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
event.EventTime = &val
|
||||
}
|
||||
|
||||
if val := headers.Get("CE-SchemaURL"); len(val) > 0 {
|
||||
event.SchemaURL = val
|
||||
}
|
||||
|
||||
event.Extensions = map[string]interface{}{}
|
||||
for key, val := range flatten(headers) {
|
||||
if strings.HasPrefix(key, "Ce-X-") {
|
||||
key = strings.TrimLeft(key, "Ce-X-")
|
||||
// Make first character lowercase
|
||||
runes := []rune(key)
|
||||
runes[0] = unicode.ToLower(runes[0])
|
||||
event.Extensions[string(runes)] = val
|
||||
}
|
||||
}
|
||||
|
||||
event.Data = normalizePayload(event.Data, event.ContentType)
|
||||
return event, nil
|
||||
}
|
||||
|
||||
func flatten(h http.Header) map[string]string {
|
||||
headers := map[string]string{}
|
||||
for key, header := range h {
|
||||
headers[key] = header[0]
|
||||
if len(header) > 1 {
|
||||
headers[key] = strings.Join(header, ", ")
|
||||
}
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
func parseAsCloudEvent(mime string, payload interface{}) (*Event, error) {
|
||||
body, ok := payload.([]byte)
|
||||
if ok {
|
||||
event := &Event{}
|
||||
err := json.Unmarshal(body, event)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = event.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
event.Data = normalizePayload(event.Data, event.ContentType)
|
||||
return event, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("couldn't cast to []byte")
|
||||
}
|
||||
|
||||
const (
|
||||
mimeJSON = "application/json"
|
||||
mimeFormMultipart = "multipart/form-data"
|
||||
mimeFormURLEncoded = "application/x-www-form-urlencoded"
|
||||
mimeCloudEventsJSON = "application/cloudevents+json"
|
||||
)
|
||||
|
||||
// normalizePayload takes anything, checks if it's []byte array and depending on provided mime
|
||||
// type converts it to either string or map[string]interface to avoid having base64 string after
|
||||
// JSON marshaling.
|
||||
func normalizePayload(payload interface{}, mime string) interface{} {
|
||||
if bytePayload, ok := payload.([]byte); ok && len(bytePayload) > 0 {
|
||||
switch {
|
||||
case mime == mimeJSON || strings.HasSuffix(mime, "+json"):
|
||||
var result map[string]interface{}
|
||||
err := json.Unmarshal(bytePayload, &result)
|
||||
if err != nil {
|
||||
return payload
|
||||
}
|
||||
return result
|
||||
case strings.HasPrefix(mime, mimeFormMultipart), mime == mimeFormURLEncoded:
|
||||
return string(bytePayload)
|
||||
}
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
// HTTPRequestData is a event schema used for sending events to HTTP subscriptions.
|
||||
type HTTPRequestData struct {
|
||||
Headers map[string]string `json:"headers"`
|
||||
Query map[string][]string `json:"query"`
|
||||
Body interface{} `json:"body"`
|
||||
Host string `json:"host"`
|
||||
Path string `json:"path"`
|
||||
Method string `json:"method"`
|
||||
Params map[string]string `json:"params"`
|
||||
}
|
||||
|
||||
// NewHTTPRequestData returns a new instance of HTTPRequestData
|
||||
func newHTTPRequestData(r *http.Request, eventData interface{}) *HTTPRequestData {
|
||||
req := &HTTPRequestData{
|
||||
Headers: flatten(r.Header),
|
||||
Query: r.URL.Query(),
|
||||
Body: eventData,
|
||||
Host: r.Host,
|
||||
Path: r.URL.Path,
|
||||
Method: r.Method,
|
||||
}
|
||||
|
||||
req.Body = normalizePayload(req.Body, r.Header.Get("content-type"))
|
||||
return req
|
||||
}
|
122
api/handler/event/event.go
Normal file
122
api/handler/event/event.go
Normal file
@@ -0,0 +1,122 @@
|
||||
// Package event provides a handler which publishes an event
|
||||
package event
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/micro/go-micro/api/handler"
|
||||
proto "github.com/micro/go-micro/api/proto"
|
||||
"github.com/micro/go-micro/util/ctx"
|
||||
"github.com/pborman/uuid"
|
||||
)
|
||||
|
||||
type event struct {
|
||||
options handler.Options
|
||||
}
|
||||
|
||||
var (
|
||||
Handler = "event"
|
||||
versionRe = regexp.MustCompilePOSIX("^v[0-9]+$")
|
||||
)
|
||||
|
||||
func eventName(parts []string) string {
|
||||
return strings.Join(parts, ".")
|
||||
}
|
||||
|
||||
func evRoute(ns, p string) (string, string) {
|
||||
p = path.Clean(p)
|
||||
p = strings.TrimPrefix(p, "/")
|
||||
|
||||
if len(p) == 0 {
|
||||
return ns, "event"
|
||||
}
|
||||
|
||||
parts := strings.Split(p, "/")
|
||||
|
||||
// no path
|
||||
if len(parts) == 0 {
|
||||
// topic: namespace
|
||||
// action: event
|
||||
return strings.Trim(ns, "."), "event"
|
||||
}
|
||||
|
||||
// Treat /v[0-9]+ as versioning
|
||||
// /v1/foo/bar => topic: v1.foo action: bar
|
||||
if len(parts) >= 2 && versionRe.Match([]byte(parts[0])) {
|
||||
topic := ns + "." + strings.Join(parts[:2], ".")
|
||||
action := eventName(parts[1:])
|
||||
return topic, action
|
||||
}
|
||||
|
||||
// /foo => topic: ns.foo action: foo
|
||||
// /foo/bar => topic: ns.foo action: bar
|
||||
topic := ns + "." + strings.Join(parts[:1], ".")
|
||||
action := eventName(parts[1:])
|
||||
|
||||
return topic, action
|
||||
}
|
||||
|
||||
func (e *event) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// request to topic:event
|
||||
// create event
|
||||
// publish to topic
|
||||
|
||||
topic, action := evRoute(e.options.Namespace, r.URL.Path)
|
||||
|
||||
// create event
|
||||
ev := &proto.Event{
|
||||
Name: action,
|
||||
// TODO: dedupe event
|
||||
Id: fmt.Sprintf("%s-%s-%s", topic, action, uuid.NewUUID().String()),
|
||||
Header: make(map[string]*proto.Pair),
|
||||
Timestamp: time.Now().Unix(),
|
||||
}
|
||||
|
||||
// set headers
|
||||
for key, vals := range r.Header {
|
||||
header, ok := ev.Header[key]
|
||||
if !ok {
|
||||
header = &proto.Pair{
|
||||
Key: key,
|
||||
}
|
||||
ev.Header[key] = header
|
||||
}
|
||||
header.Values = vals
|
||||
}
|
||||
|
||||
// set body
|
||||
b, err := ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
ev.Data = string(b)
|
||||
|
||||
// get client
|
||||
c := e.options.Service.Client()
|
||||
|
||||
// create publication
|
||||
p := c.NewMessage(topic, ev)
|
||||
|
||||
// publish event
|
||||
if err := c.Publish(ctx.FromRequest(r), p); err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (e *event) String() string {
|
||||
return "event"
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
return &event{
|
||||
options: handler.NewOptions(opts...),
|
||||
}
|
||||
}
|
16
api/handler/file/file.go
Normal file
16
api/handler/file/file.go
Normal file
@@ -0,0 +1,16 @@
|
||||
// Package file serves file relative to the current directory
|
||||
package file
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Handler struct{}
|
||||
|
||||
func (h *Handler) Serve(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, "."+r.URL.Path)
|
||||
}
|
||||
|
||||
func (h *Handler) String() string {
|
||||
return "file"
|
||||
}
|
14
api/handler/handler.go
Normal file
14
api/handler/handler.go
Normal file
@@ -0,0 +1,14 @@
|
||||
// Package handler provides http handlers
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Handler represents a HTTP handler that manages a request
|
||||
type Handler interface {
|
||||
// standard http handler
|
||||
http.Handler
|
||||
// name of handler
|
||||
String() string
|
||||
}
|
100
api/handler/http/http.go
Normal file
100
api/handler/http/http.go
Normal file
@@ -0,0 +1,100 @@
|
||||
// Package http is a http reverse proxy handler
|
||||
package http
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
|
||||
"github.com/micro/go-micro/api"
|
||||
"github.com/micro/go-micro/api/handler"
|
||||
"github.com/micro/go-micro/selector"
|
||||
)
|
||||
|
||||
const (
|
||||
Handler = "http"
|
||||
)
|
||||
|
||||
type httpHandler struct {
|
||||
options handler.Options
|
||||
|
||||
// set with different initialiser
|
||||
s *api.Service
|
||||
}
|
||||
|
||||
func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
service, err := h.getService(r)
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
|
||||
if len(service) == 0 {
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
|
||||
rp, err := url.Parse(service)
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
|
||||
httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// getService returns the service for this request from the selector
|
||||
func (h *httpHandler) getService(r *http.Request) (string, error) {
|
||||
var service *api.Service
|
||||
|
||||
if h.s != nil {
|
||||
// we were given the service
|
||||
service = h.s
|
||||
} else if h.options.Router != nil {
|
||||
// try get service from router
|
||||
s, err := h.options.Router.Route(r)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
service = s
|
||||
} else {
|
||||
// we have no way of routing the request
|
||||
return "", errors.New("no route found")
|
||||
}
|
||||
|
||||
// create a random selector
|
||||
next := selector.Random(service.Services)
|
||||
|
||||
// get the next node
|
||||
s, err := next()
|
||||
if err != nil {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
return fmt.Sprintf("http://%s:%d", s.Address, s.Port), nil
|
||||
}
|
||||
|
||||
func (h *httpHandler) String() string {
|
||||
return "http"
|
||||
}
|
||||
|
||||
// NewHandler returns a http proxy handler
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
|
||||
return &httpHandler{
|
||||
options: options,
|
||||
}
|
||||
}
|
||||
|
||||
// WithService creates a handler with a service
|
||||
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
|
||||
return &httpHandler{
|
||||
options: options,
|
||||
s: s,
|
||||
}
|
||||
}
|
133
api/handler/http/http_test.go
Normal file
133
api/handler/http/http_test.go
Normal file
@@ -0,0 +1,133 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/micro/go-micro/api/handler"
|
||||
"github.com/micro/go-micro/api/router"
|
||||
regRouter "github.com/micro/go-micro/api/router/registry"
|
||||
"github.com/micro/go-micro/cmd"
|
||||
"github.com/micro/go-micro/registry"
|
||||
"github.com/micro/go-micro/registry/memory"
|
||||
)
|
||||
|
||||
func testHttp(t *testing.T, path, service, ns string) {
|
||||
r := memory.NewRegistry()
|
||||
cmd.DefaultCmd = cmd.NewCmd(cmd.Registry(&r))
|
||||
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
parts := strings.Split(l.Addr().String(), ":")
|
||||
|
||||
var host string
|
||||
var port int
|
||||
|
||||
host = parts[0]
|
||||
port, _ = strconv.Atoi(parts[1])
|
||||
|
||||
s := ®istry.Service{
|
||||
Name: service,
|
||||
Nodes: []*registry.Node{
|
||||
®istry.Node{
|
||||
Id: service + "-1",
|
||||
Address: host,
|
||||
Port: port,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
r.Register(s)
|
||||
defer r.Deregister(s)
|
||||
|
||||
// setup the test handler
|
||||
m := http.NewServeMux()
|
||||
m.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`you got served`))
|
||||
})
|
||||
|
||||
// start http test serve
|
||||
go http.Serve(l, m)
|
||||
|
||||
// create new request and writer
|
||||
w := httptest.NewRecorder()
|
||||
req, err := http.NewRequest("POST", path, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// initialise the handler
|
||||
rt := regRouter.NewRouter(
|
||||
router.WithHandler("http"),
|
||||
router.WithNamespace(ns),
|
||||
)
|
||||
|
||||
p := NewHandler(handler.WithRouter(rt))
|
||||
|
||||
// execute the handler
|
||||
p.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("Expected 200 response got %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
if w.Body.String() != "you got served" {
|
||||
t.Fatalf("Expected body: you got served. Got: %s", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHttpHandler(t *testing.T) {
|
||||
testData := []struct {
|
||||
path string
|
||||
service string
|
||||
namespace string
|
||||
}{
|
||||
{
|
||||
"/test/foo",
|
||||
"go.micro.api.test",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/test/foo/baz",
|
||||
"go.micro.api.test",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v1/foo",
|
||||
"go.micro.api.v1.foo",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v1/foo/bar",
|
||||
"go.micro.api.v1.foo",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v2/baz",
|
||||
"go.micro.api.v2.baz",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v2/baz/bar",
|
||||
"go.micro.api.v2.baz",
|
||||
"go.micro.api",
|
||||
},
|
||||
{
|
||||
"/v2/baz/bar",
|
||||
"v2.baz",
|
||||
"",
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range testData {
|
||||
testHttp(t, d.path, d.service, d.namespace)
|
||||
}
|
||||
}
|
55
api/handler/options.go
Normal file
55
api/handler/options.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/micro/go-micro"
|
||||
"github.com/micro/go-micro/api/router"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
Namespace string
|
||||
Router router.Router
|
||||
Service micro.Service
|
||||
}
|
||||
|
||||
type Option func(o *Options)
|
||||
|
||||
// NewOptions fills in the blanks
|
||||
func NewOptions(opts ...Option) Options {
|
||||
var options Options
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
// create service if its blank
|
||||
if options.Service == nil {
|
||||
WithService(micro.NewService())(&options)
|
||||
}
|
||||
|
||||
// set namespace if blank
|
||||
if len(options.Namespace) == 0 {
|
||||
WithNamespace("go.micro.api")(&options)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
// WithNamespace specifies the namespace for the handler
|
||||
func WithNamespace(s string) Option {
|
||||
return func(o *Options) {
|
||||
o.Namespace = s
|
||||
}
|
||||
}
|
||||
|
||||
// WithRouter specifies a router to be used by the handler
|
||||
func WithRouter(r router.Router) Option {
|
||||
return func(o *Options) {
|
||||
o.Router = r
|
||||
}
|
||||
}
|
||||
|
||||
// WithService specifies a micro.Service
|
||||
func WithService(s micro.Service) Option {
|
||||
return func(o *Options) {
|
||||
o.Service = s
|
||||
}
|
||||
}
|
211
api/handler/registry/registry.go
Normal file
211
api/handler/registry/registry.go
Normal file
@@ -0,0 +1,211 @@
|
||||
// Package registry is a go-micro/registry handler
|
||||
package registry
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/micro/go-micro/api/handler"
|
||||
"github.com/micro/go-micro/registry"
|
||||
)
|
||||
|
||||
const (
|
||||
Handler = "registry"
|
||||
|
||||
pingTime = (readDeadline * 9) / 10
|
||||
readLimit = 16384
|
||||
readDeadline = 60 * time.Second
|
||||
writeDeadline = 10 * time.Second
|
||||
)
|
||||
|
||||
type registryHandler struct {
|
||||
opts handler.Options
|
||||
reg registry.Registry
|
||||
}
|
||||
|
||||
func (rh *registryHandler) add(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
b, err := ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var opts []registry.RegisterOption
|
||||
|
||||
// parse ttl
|
||||
if ttl := r.Form.Get("ttl"); len(ttl) > 0 {
|
||||
d, err := time.ParseDuration(ttl)
|
||||
if err == nil {
|
||||
opts = append(opts, registry.RegisterTTL(d))
|
||||
}
|
||||
}
|
||||
|
||||
var service *registry.Service
|
||||
err = json.Unmarshal(b, &service)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
err = rh.reg.Register(service, opts...)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (rh *registryHandler) del(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
b, err := ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var service *registry.Service
|
||||
err = json.Unmarshal(b, &service)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
err = rh.reg.Deregister(service)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (rh *registryHandler) get(w http.ResponseWriter, r *http.Request) {
|
||||
r.ParseForm()
|
||||
service := r.Form.Get("service")
|
||||
|
||||
var s []*registry.Service
|
||||
var err error
|
||||
|
||||
if len(service) == 0 {
|
||||
//
|
||||
upgrade := r.Header.Get("Upgrade")
|
||||
connect := r.Header.Get("Connection")
|
||||
|
||||
// watch if websockets
|
||||
if upgrade == "websocket" && connect == "Upgrade" {
|
||||
rw, err := rh.reg.Watch()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
watch(rw, w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// otherwise list services
|
||||
s, err = rh.reg.ListServices()
|
||||
} else {
|
||||
s, err = rh.reg.GetService(service)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
|
||||
if s == nil || (len(service) > 0 && (len(s) == 0 || len(s[0].Name) == 0)) {
|
||||
http.Error(w, "Service not found", 404)
|
||||
return
|
||||
}
|
||||
|
||||
b, err := json.Marshal(s)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(b)))
|
||||
w.Write(b)
|
||||
}
|
||||
|
||||
func ping(ws *websocket.Conn, exit chan bool) {
|
||||
ticker := time.NewTicker(pingTime)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
ws.SetWriteDeadline(time.Now().Add(writeDeadline))
|
||||
err := ws.WriteMessage(websocket.PingMessage, []byte{})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
case <-exit:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func watch(rw registry.Watcher, w http.ResponseWriter, r *http.Request) {
|
||||
upgrader := websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
}
|
||||
|
||||
ws, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
|
||||
// we need an exit chan
|
||||
exit := make(chan bool)
|
||||
|
||||
defer func() {
|
||||
close(exit)
|
||||
}()
|
||||
|
||||
// ping the socket
|
||||
go ping(ws, exit)
|
||||
|
||||
for {
|
||||
// get next result
|
||||
r, err := rw.Next()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
|
||||
// write to client
|
||||
ws.SetWriteDeadline(time.Now().Add(writeDeadline))
|
||||
if err := ws.WriteJSON(r); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (rh *registryHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
rh.get(w, r)
|
||||
case "POST":
|
||||
rh.add(w, r)
|
||||
case "DELETE":
|
||||
rh.del(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (rh *registryHandler) String() string {
|
||||
return "registry"
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
|
||||
return ®istryHandler{
|
||||
opts: options,
|
||||
reg: options.Service.Client().Options().Registry,
|
||||
}
|
||||
}
|
307
api/handler/rpc/rpc.go
Normal file
307
api/handler/rpc/rpc.go
Normal file
@@ -0,0 +1,307 @@
|
||||
// Package rpc is a go-micro rpc handler.
|
||||
package rpc
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/joncalhoun/qson"
|
||||
"github.com/micro/go-micro/api"
|
||||
"github.com/micro/go-micro/api/handler"
|
||||
proto "github.com/micro/go-micro/api/internal/proto"
|
||||
"github.com/micro/go-micro/client"
|
||||
"github.com/micro/go-micro/codec"
|
||||
"github.com/micro/go-micro/codec/jsonrpc"
|
||||
"github.com/micro/go-micro/codec/protorpc"
|
||||
"github.com/micro/go-micro/errors"
|
||||
"github.com/micro/go-micro/registry"
|
||||
"github.com/micro/go-micro/selector"
|
||||
"github.com/micro/go-micro/util/ctx"
|
||||
)
|
||||
|
||||
const (
|
||||
Handler = "rpc"
|
||||
)
|
||||
|
||||
var (
|
||||
// supported json codecs
|
||||
jsonCodecs = []string{
|
||||
"application/grpc+json",
|
||||
"application/json",
|
||||
"application/json-rpc",
|
||||
}
|
||||
|
||||
// support proto codecs
|
||||
protoCodecs = []string{
|
||||
"application/grpc",
|
||||
"application/grpc+proto",
|
||||
"application/proto",
|
||||
"application/protobuf",
|
||||
"application/proto-rpc",
|
||||
"application/octet-stream",
|
||||
}
|
||||
)
|
||||
|
||||
type rpcHandler struct {
|
||||
opts handler.Options
|
||||
s *api.Service
|
||||
}
|
||||
|
||||
type buffer struct {
|
||||
io.ReadCloser
|
||||
}
|
||||
|
||||
func (b *buffer) Write(_ []byte) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// strategy is a hack for selection
|
||||
func strategy(services []*registry.Service) selector.Strategy {
|
||||
return func(_ []*registry.Service) selector.Next {
|
||||
// ignore input to this function, use services above
|
||||
return selector.Random(services)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
defer r.Body.Close()
|
||||
var service *api.Service
|
||||
|
||||
if h.s != nil {
|
||||
// we were given the service
|
||||
service = h.s
|
||||
} else if h.opts.Router != nil {
|
||||
// try get service from router
|
||||
s, err := h.opts.Router.Route(r)
|
||||
if err != nil {
|
||||
writeError(w, r, errors.InternalServerError("go.micro.api", err.Error()))
|
||||
return
|
||||
}
|
||||
service = s
|
||||
} else {
|
||||
// we have no way of routing the request
|
||||
writeError(w, r, errors.InternalServerError("go.micro.api", "no route found"))
|
||||
return
|
||||
}
|
||||
|
||||
// only allow post when we have the router
|
||||
if r.Method != "GET" && (h.opts.Router != nil && r.Method != "POST") {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
ct := r.Header.Get("Content-Type")
|
||||
|
||||
// Strip charset from Content-Type (like `application/json; charset=UTF-8`)
|
||||
if idx := strings.IndexRune(ct, ';'); idx >= 0 {
|
||||
ct = ct[:idx]
|
||||
}
|
||||
|
||||
// micro client
|
||||
c := h.opts.Service.Client()
|
||||
|
||||
// create strategy
|
||||
so := selector.WithStrategy(strategy(service.Services))
|
||||
|
||||
// get payload
|
||||
br, err := requestPayload(r)
|
||||
if err != nil {
|
||||
writeError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
// create context
|
||||
cx := ctx.FromRequest(r)
|
||||
|
||||
var rsp []byte
|
||||
|
||||
switch {
|
||||
// json codecs
|
||||
case hasCodec(ct, jsonCodecs):
|
||||
var request json.RawMessage
|
||||
// if the extracted payload isn't empty lets use it
|
||||
if len(br) > 0 {
|
||||
request = json.RawMessage(br)
|
||||
}
|
||||
|
||||
// create request/response
|
||||
var response json.RawMessage
|
||||
|
||||
req := c.NewRequest(
|
||||
service.Name,
|
||||
service.Endpoint.Name,
|
||||
&request,
|
||||
client.WithContentType(ct),
|
||||
)
|
||||
|
||||
// make the call
|
||||
if err := c.Call(cx, req, &response, client.WithSelectOption(so)); err != nil {
|
||||
writeError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
// marshall response
|
||||
rsp, _ = response.MarshalJSON()
|
||||
// proto codecs
|
||||
case hasCodec(ct, protoCodecs):
|
||||
request := &proto.Message{}
|
||||
// if the extracted payload isn't empty lets use it
|
||||
if len(br) > 0 {
|
||||
request = proto.NewMessage(br)
|
||||
}
|
||||
|
||||
// create request/response
|
||||
response := &proto.Message{}
|
||||
|
||||
req := c.NewRequest(
|
||||
service.Name,
|
||||
service.Endpoint.Name,
|
||||
request,
|
||||
client.WithContentType(ct),
|
||||
)
|
||||
|
||||
// make the call
|
||||
if err := c.Call(cx, req, response, client.WithSelectOption(so)); err != nil {
|
||||
writeError(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
// marshall response
|
||||
rsp, _ = response.Marshal()
|
||||
default:
|
||||
http.Error(w, "Unsupported Content-Type", 400)
|
||||
return
|
||||
}
|
||||
|
||||
// write the response
|
||||
writeResponse(w, r, rsp)
|
||||
}
|
||||
|
||||
func (rh *rpcHandler) String() string {
|
||||
return "rpc"
|
||||
}
|
||||
|
||||
func hasCodec(ct string, codecs []string) bool {
|
||||
for _, codec := range codecs {
|
||||
if ct == codec {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// requestPayload takes a *http.Request.
|
||||
// If the request is a GET the query string parameters are extracted and marshaled to JSON and the raw bytes are returned.
|
||||
// If the request method is a POST the request body is read and returned
|
||||
func requestPayload(r *http.Request) ([]byte, error) {
|
||||
// we have to decode json-rpc and proto-rpc because we suck
|
||||
// well actually because there's no proxy codec right now
|
||||
switch r.Header.Get("Content-Type") {
|
||||
case "application/json-rpc":
|
||||
msg := codec.Message{
|
||||
Type: codec.Request,
|
||||
Header: make(map[string]string),
|
||||
}
|
||||
c := jsonrpc.NewCodec(&buffer{r.Body})
|
||||
if err := c.ReadHeader(&msg, codec.Request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var raw json.RawMessage
|
||||
if err := c.ReadBody(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ([]byte)(raw), nil
|
||||
case "application/proto-rpc", "application/octet-stream":
|
||||
msg := codec.Message{
|
||||
Type: codec.Request,
|
||||
Header: make(map[string]string),
|
||||
}
|
||||
c := protorpc.NewCodec(&buffer{r.Body})
|
||||
if err := c.ReadHeader(&msg, codec.Request); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var raw proto.Message
|
||||
if err := c.ReadBody(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, _ := raw.Marshal()
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// otherwise as per usual
|
||||
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
if len(r.URL.RawQuery) > 0 {
|
||||
return qson.ToJSON(r.URL.RawQuery)
|
||||
}
|
||||
case "PATCH", "POST":
|
||||
return ioutil.ReadAll(r.Body)
|
||||
}
|
||||
|
||||
return []byte{}, nil
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
ce := errors.Parse(err.Error())
|
||||
|
||||
switch ce.Code {
|
||||
case 0:
|
||||
// assuming it's totally screwed
|
||||
ce.Code = 500
|
||||
ce.Id = "go.micro.api"
|
||||
ce.Status = http.StatusText(500)
|
||||
ce.Detail = "error during request: " + ce.Detail
|
||||
w.WriteHeader(500)
|
||||
default:
|
||||
w.WriteHeader(int(ce.Code))
|
||||
}
|
||||
|
||||
// response content type
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
// Set trailers
|
||||
if strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
|
||||
w.Header().Set("Trailer", "grpc-status")
|
||||
w.Header().Set("Trailer", "grpc-message")
|
||||
w.Header().Set("grpc-status", "13")
|
||||
w.Header().Set("grpc-message", ce.Detail)
|
||||
}
|
||||
|
||||
w.Write([]byte(ce.Error()))
|
||||
}
|
||||
|
||||
func writeResponse(w http.ResponseWriter, r *http.Request, rsp []byte) {
|
||||
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(rsp)))
|
||||
|
||||
// Set trailers
|
||||
if strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
|
||||
w.Header().Set("Trailer", "grpc-status")
|
||||
w.Header().Set("Trailer", "grpc-message")
|
||||
w.Header().Set("grpc-status", "0")
|
||||
w.Header().Set("grpc-message", "")
|
||||
}
|
||||
|
||||
// write response
|
||||
w.Write(rsp)
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
return &rpcHandler{
|
||||
opts: options,
|
||||
}
|
||||
}
|
||||
|
||||
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
return &rpcHandler{
|
||||
opts: options,
|
||||
s: s,
|
||||
}
|
||||
}
|
95
api/handler/rpc/rpc_test.go
Normal file
95
api/handler/rpc/rpc_test.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package rpc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/micro/go-micro/api/proto"
|
||||
)
|
||||
|
||||
func TestRequestPayloadFromRequest(t *testing.T) {
|
||||
|
||||
// our test event so that we can validate serialising / deserializing of true protos works
|
||||
protoEvent := go_api.Event{
|
||||
Name: "Test",
|
||||
}
|
||||
|
||||
protoBytes, err := proto.Marshal(&protoEvent)
|
||||
if err != nil {
|
||||
t.Fatal("Failed to marshal proto", err)
|
||||
}
|
||||
|
||||
jsonBytes, err := json.Marshal(protoEvent)
|
||||
if err != nil {
|
||||
t.Fatal("Failed to marshal proto to JSON ", err)
|
||||
}
|
||||
|
||||
t.Run("extracting a proto from a POST request", func(t *testing.T) {
|
||||
r, err := http.NewRequest("POST", "http://localhost/my/path", bytes.NewReader(protoBytes))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to created http.Request: %v", err)
|
||||
}
|
||||
|
||||
extByte, err := requestPayload(r)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to extract payload from request: %v", err)
|
||||
}
|
||||
if string(extByte) != string(protoBytes) {
|
||||
t.Fatalf("Expected %v and %v to match", string(extByte), string(protoBytes))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("extracting JSON from a POST request", func(t *testing.T) {
|
||||
r, err := http.NewRequest("POST", "http://localhost/my/path", bytes.NewReader(jsonBytes))
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to created http.Request: %v", err)
|
||||
}
|
||||
|
||||
extByte, err := requestPayload(r)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to extract payload from request: %v", err)
|
||||
}
|
||||
if string(extByte) != string(jsonBytes) {
|
||||
t.Fatalf("Expected %v and %v to match", string(extByte), string(jsonBytes))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("extracting params from a GET request", func(t *testing.T) {
|
||||
|
||||
r, err := http.NewRequest("GET", "http://localhost/my/path", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to created http.Request: %v", err)
|
||||
}
|
||||
|
||||
q := r.URL.Query()
|
||||
q.Add("name", "Test")
|
||||
r.URL.RawQuery = q.Encode()
|
||||
|
||||
extByte, err := requestPayload(r)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to extract payload from request: %v", err)
|
||||
}
|
||||
if string(extByte) != string(jsonBytes) {
|
||||
t.Fatalf("Expected %v and %v to match", string(extByte), string(jsonBytes))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GET request with no params", func(t *testing.T) {
|
||||
|
||||
r, err := http.NewRequest("GET", "http://localhost/my/path", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to created http.Request: %v", err)
|
||||
}
|
||||
|
||||
extByte, err := requestPayload(r)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to extract payload from request: %v", err)
|
||||
}
|
||||
if string(extByte) != "" {
|
||||
t.Fatalf("Expected %v and %v to match", string(extByte), "")
|
||||
}
|
||||
})
|
||||
}
|
25
api/handler/udp/udp.go
Normal file
25
api/handler/udp/udp.go
Normal file
@@ -0,0 +1,25 @@
|
||||
// Package udp reads and write from a udp connection
|
||||
package udp
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Handler struct{}
|
||||
|
||||
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
c, err := net.Dial("udp", r.Host)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
go io.Copy(c, r.Body)
|
||||
// write response
|
||||
io.Copy(w, c)
|
||||
}
|
||||
|
||||
func (h *Handler) String() string {
|
||||
return "udp"
|
||||
}
|
30
api/handler/unix/unix.go
Normal file
30
api/handler/unix/unix.go
Normal file
@@ -0,0 +1,30 @@
|
||||
// Package unix reads from a unix socket expecting it to be in /tmp/path
|
||||
package unix
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type Handler struct{}
|
||||
|
||||
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
sock := fmt.Sprintf("%s.sock", filepath.Clean(r.URL.Path))
|
||||
path := filepath.Join("/tmp", sock)
|
||||
|
||||
c, err := net.Dial("unix", path)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
go io.Copy(c, r.Body)
|
||||
// write response
|
||||
io.Copy(w, c)
|
||||
}
|
||||
|
||||
func (h *Handler) String() string {
|
||||
return "unix"
|
||||
}
|
177
api/handler/web/web.go
Normal file
177
api/handler/web/web.go
Normal file
@@ -0,0 +1,177 @@
|
||||
// Package web contains the web handler including websocket support
|
||||
package web
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/micro/go-micro/api"
|
||||
"github.com/micro/go-micro/api/handler"
|
||||
"github.com/micro/go-micro/selector"
|
||||
)
|
||||
|
||||
const (
|
||||
Handler = "web"
|
||||
)
|
||||
|
||||
type webHandler struct {
|
||||
opts handler.Options
|
||||
s *api.Service
|
||||
}
|
||||
|
||||
func (wh *webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
service, err := wh.getService(r)
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
|
||||
if len(service) == 0 {
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
|
||||
rp, err := url.Parse(service)
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
return
|
||||
}
|
||||
|
||||
if isWebSocket(r) {
|
||||
wh.serveWebSocket(rp.Host, w, r)
|
||||
return
|
||||
}
|
||||
|
||||
httputil.NewSingleHostReverseProxy(rp).ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// getService returns the service for this request from the selector
|
||||
func (wh *webHandler) getService(r *http.Request) (string, error) {
|
||||
var service *api.Service
|
||||
|
||||
if wh.s != nil {
|
||||
// we were given the service
|
||||
service = wh.s
|
||||
} else if wh.opts.Router != nil {
|
||||
// try get service from router
|
||||
s, err := wh.opts.Router.Route(r)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
service = s
|
||||
} else {
|
||||
// we have no way of routing the request
|
||||
return "", errors.New("no route found")
|
||||
}
|
||||
|
||||
// create a random selector
|
||||
next := selector.Random(service.Services)
|
||||
|
||||
// get the next node
|
||||
s, err := next()
|
||||
if err != nil {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
return fmt.Sprintf("http://%s:%d", s.Address, s.Port), nil
|
||||
}
|
||||
|
||||
// serveWebSocket used to serve a web socket proxied connection
|
||||
func (wh *webHandler) serveWebSocket(host string, w http.ResponseWriter, r *http.Request) {
|
||||
req := new(http.Request)
|
||||
*req = *r
|
||||
|
||||
if len(host) == 0 {
|
||||
http.Error(w, "invalid host", 500)
|
||||
return
|
||||
}
|
||||
|
||||
// set x-forward-for
|
||||
if clientIP, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||
if ips, ok := req.Header["X-Forwarded-For"]; ok {
|
||||
clientIP = strings.Join(ips, ", ") + ", " + clientIP
|
||||
}
|
||||
req.Header.Set("X-Forwarded-For", clientIP)
|
||||
}
|
||||
|
||||
// connect to the backend host
|
||||
conn, err := net.Dial("tcp", host)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 500)
|
||||
return
|
||||
}
|
||||
|
||||
// hijack the connection
|
||||
hj, ok := w.(http.Hijacker)
|
||||
if !ok {
|
||||
http.Error(w, "failed to connect", 500)
|
||||
return
|
||||
}
|
||||
|
||||
nc, _, err := hj.Hijack()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
defer nc.Close()
|
||||
defer conn.Close()
|
||||
|
||||
if err = req.Write(conn); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
errCh := make(chan error, 2)
|
||||
|
||||
cp := func(dst io.Writer, src io.Reader) {
|
||||
_, err := io.Copy(dst, src)
|
||||
errCh <- err
|
||||
}
|
||||
|
||||
go cp(conn, nc)
|
||||
go cp(nc, conn)
|
||||
|
||||
<-errCh
|
||||
}
|
||||
|
||||
func isWebSocket(r *http.Request) bool {
|
||||
contains := func(key, val string) bool {
|
||||
vv := strings.Split(r.Header.Get(key), ",")
|
||||
for _, v := range vv {
|
||||
if val == strings.ToLower(strings.TrimSpace(v)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
if contains("Connection", "upgrade") && contains("Upgrade", "websocket") {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (wh *webHandler) String() string {
|
||||
return "web"
|
||||
}
|
||||
|
||||
func NewHandler(opts ...handler.Option) handler.Handler {
|
||||
return &webHandler{
|
||||
opts: handler.NewOptions(opts...),
|
||||
}
|
||||
}
|
||||
|
||||
func WithService(s *api.Service, opts ...handler.Option) handler.Handler {
|
||||
options := handler.NewOptions(opts...)
|
||||
|
||||
return &webHandler{
|
||||
opts: options,
|
||||
s: s,
|
||||
}
|
||||
}
|
28
api/internal/proto/message.pb.go
Normal file
28
api/internal/proto/message.pb.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package proto
|
||||
|
||||
type Message struct {
|
||||
data []byte
|
||||
}
|
||||
|
||||
func (m *Message) ProtoMessage() {}
|
||||
|
||||
func (m *Message) Reset() {
|
||||
*m = Message{}
|
||||
}
|
||||
|
||||
func (m *Message) String() string {
|
||||
return string(m.data)
|
||||
}
|
||||
|
||||
func (m *Message) Marshal() ([]byte, error) {
|
||||
return m.data, nil
|
||||
}
|
||||
|
||||
func (m *Message) Unmarshal(data []byte) error {
|
||||
m.data = data
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewMessage(data []byte) *Message {
|
||||
return &Message{data}
|
||||
}
|
31
api/proto/api.micro.go
Normal file
31
api/proto/api.micro.go
Normal file
@@ -0,0 +1,31 @@
|
||||
// Code generated by protoc-gen-micro. DO NOT EDIT.
|
||||
// source: github.com/micro/go-micro/api/proto/api.proto
|
||||
|
||||
/*
|
||||
Package go_api is a generated protocol buffer package.
|
||||
|
||||
It is generated from these files:
|
||||
github.com/micro/go-micro/api/proto/api.proto
|
||||
|
||||
It has these top-level messages:
|
||||
Pair
|
||||
Request
|
||||
Response
|
||||
Event
|
||||
*/
|
||||
package go_api
|
||||
|
||||
import proto "github.com/golang/protobuf/proto"
|
||||
import fmt "fmt"
|
||||
import math "math"
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var _ = proto.Marshal
|
||||
var _ = fmt.Errorf
|
||||
var _ = math.Inf
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the proto package it is being compiled against.
|
||||
// A compilation error at this line likely means your copy of the
|
||||
// proto package needs to be updated.
|
||||
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
|
332
api/proto/api.pb.go
Normal file
332
api/proto/api.pb.go
Normal file
@@ -0,0 +1,332 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// source: github.com/micro/go-micro/api/proto/api.proto
|
||||
|
||||
package go_api
|
||||
|
||||
import proto "github.com/golang/protobuf/proto"
|
||||
import fmt "fmt"
|
||||
import math "math"
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var _ = proto.Marshal
|
||||
var _ = fmt.Errorf
|
||||
var _ = math.Inf
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the proto package it is being compiled against.
|
||||
// A compilation error at this line likely means your copy of the
|
||||
// proto package needs to be updated.
|
||||
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
|
||||
|
||||
type Pair struct {
|
||||
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
|
||||
Values []string `protobuf:"bytes,2,rep,name=values,proto3" json:"values,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *Pair) Reset() { *m = Pair{} }
|
||||
func (m *Pair) String() string { return proto.CompactTextString(m) }
|
||||
func (*Pair) ProtoMessage() {}
|
||||
func (*Pair) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_api_17a7876430d97ebd, []int{0}
|
||||
}
|
||||
func (m *Pair) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_Pair.Unmarshal(m, b)
|
||||
}
|
||||
func (m *Pair) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_Pair.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (dst *Pair) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_Pair.Merge(dst, src)
|
||||
}
|
||||
func (m *Pair) XXX_Size() int {
|
||||
return xxx_messageInfo_Pair.Size(m)
|
||||
}
|
||||
func (m *Pair) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_Pair.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_Pair proto.InternalMessageInfo
|
||||
|
||||
func (m *Pair) GetKey() string {
|
||||
if m != nil {
|
||||
return m.Key
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *Pair) GetValues() []string {
|
||||
if m != nil {
|
||||
return m.Values
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// A HTTP request as RPC
|
||||
// Forward by the api handler
|
||||
type Request struct {
|
||||
Method string `protobuf:"bytes,1,opt,name=method,proto3" json:"method,omitempty"`
|
||||
Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
|
||||
Header map[string]*Pair `protobuf:"bytes,3,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
Get map[string]*Pair `protobuf:"bytes,4,rep,name=get,proto3" json:"get,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
Post map[string]*Pair `protobuf:"bytes,5,rep,name=post,proto3" json:"post,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
Body string `protobuf:"bytes,6,opt,name=body,proto3" json:"body,omitempty"`
|
||||
Url string `protobuf:"bytes,7,opt,name=url,proto3" json:"url,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *Request) Reset() { *m = Request{} }
|
||||
func (m *Request) String() string { return proto.CompactTextString(m) }
|
||||
func (*Request) ProtoMessage() {}
|
||||
func (*Request) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_api_17a7876430d97ebd, []int{1}
|
||||
}
|
||||
func (m *Request) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_Request.Unmarshal(m, b)
|
||||
}
|
||||
func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_Request.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (dst *Request) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_Request.Merge(dst, src)
|
||||
}
|
||||
func (m *Request) XXX_Size() int {
|
||||
return xxx_messageInfo_Request.Size(m)
|
||||
}
|
||||
func (m *Request) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_Request.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_Request proto.InternalMessageInfo
|
||||
|
||||
func (m *Request) GetMethod() string {
|
||||
if m != nil {
|
||||
return m.Method
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *Request) GetPath() string {
|
||||
if m != nil {
|
||||
return m.Path
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *Request) GetHeader() map[string]*Pair {
|
||||
if m != nil {
|
||||
return m.Header
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Request) GetGet() map[string]*Pair {
|
||||
if m != nil {
|
||||
return m.Get
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Request) GetPost() map[string]*Pair {
|
||||
if m != nil {
|
||||
return m.Post
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Request) GetBody() string {
|
||||
if m != nil {
|
||||
return m.Body
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *Request) GetUrl() string {
|
||||
if m != nil {
|
||||
return m.Url
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// A HTTP response as RPC
|
||||
// Expected response for the api handler
|
||||
type Response struct {
|
||||
StatusCode int32 `protobuf:"varint,1,opt,name=statusCode,proto3" json:"statusCode,omitempty"`
|
||||
Header map[string]*Pair `protobuf:"bytes,2,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
Body string `protobuf:"bytes,3,opt,name=body,proto3" json:"body,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *Response) Reset() { *m = Response{} }
|
||||
func (m *Response) String() string { return proto.CompactTextString(m) }
|
||||
func (*Response) ProtoMessage() {}
|
||||
func (*Response) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_api_17a7876430d97ebd, []int{2}
|
||||
}
|
||||
func (m *Response) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_Response.Unmarshal(m, b)
|
||||
}
|
||||
func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_Response.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (dst *Response) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_Response.Merge(dst, src)
|
||||
}
|
||||
func (m *Response) XXX_Size() int {
|
||||
return xxx_messageInfo_Response.Size(m)
|
||||
}
|
||||
func (m *Response) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_Response.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_Response proto.InternalMessageInfo
|
||||
|
||||
func (m *Response) GetStatusCode() int32 {
|
||||
if m != nil {
|
||||
return m.StatusCode
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *Response) GetHeader() map[string]*Pair {
|
||||
if m != nil {
|
||||
return m.Header
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Response) GetBody() string {
|
||||
if m != nil {
|
||||
return m.Body
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// A HTTP event as RPC
|
||||
// Forwarded by the event handler
|
||||
type Event struct {
|
||||
// e.g login
|
||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
||||
// uuid
|
||||
Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"`
|
||||
// unix timestamp of event
|
||||
Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
|
||||
// event headers
|
||||
Header map[string]*Pair `protobuf:"bytes,4,rep,name=header,proto3" json:"header,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
|
||||
// the event data
|
||||
Data string `protobuf:"bytes,5,opt,name=data,proto3" json:"data,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
}
|
||||
|
||||
func (m *Event) Reset() { *m = Event{} }
|
||||
func (m *Event) String() string { return proto.CompactTextString(m) }
|
||||
func (*Event) ProtoMessage() {}
|
||||
func (*Event) Descriptor() ([]byte, []int) {
|
||||
return fileDescriptor_api_17a7876430d97ebd, []int{3}
|
||||
}
|
||||
func (m *Event) XXX_Unmarshal(b []byte) error {
|
||||
return xxx_messageInfo_Event.Unmarshal(m, b)
|
||||
}
|
||||
func (m *Event) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
|
||||
return xxx_messageInfo_Event.Marshal(b, m, deterministic)
|
||||
}
|
||||
func (dst *Event) XXX_Merge(src proto.Message) {
|
||||
xxx_messageInfo_Event.Merge(dst, src)
|
||||
}
|
||||
func (m *Event) XXX_Size() int {
|
||||
return xxx_messageInfo_Event.Size(m)
|
||||
}
|
||||
func (m *Event) XXX_DiscardUnknown() {
|
||||
xxx_messageInfo_Event.DiscardUnknown(m)
|
||||
}
|
||||
|
||||
var xxx_messageInfo_Event proto.InternalMessageInfo
|
||||
|
||||
func (m *Event) GetName() string {
|
||||
if m != nil {
|
||||
return m.Name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *Event) GetId() string {
|
||||
if m != nil {
|
||||
return m.Id
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *Event) GetTimestamp() int64 {
|
||||
if m != nil {
|
||||
return m.Timestamp
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *Event) GetHeader() map[string]*Pair {
|
||||
if m != nil {
|
||||
return m.Header
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Event) GetData() string {
|
||||
if m != nil {
|
||||
return m.Data
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func init() {
|
||||
proto.RegisterType((*Pair)(nil), "go.api.Pair")
|
||||
proto.RegisterType((*Request)(nil), "go.api.Request")
|
||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Request.GetEntry")
|
||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Request.HeaderEntry")
|
||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Request.PostEntry")
|
||||
proto.RegisterType((*Response)(nil), "go.api.Response")
|
||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Response.HeaderEntry")
|
||||
proto.RegisterType((*Event)(nil), "go.api.Event")
|
||||
proto.RegisterMapType((map[string]*Pair)(nil), "go.api.Event.HeaderEntry")
|
||||
}
|
||||
|
||||
func init() {
|
||||
proto.RegisterFile("github.com/micro/go-micro/api/proto/api.proto", fileDescriptor_api_17a7876430d97ebd)
|
||||
}
|
||||
|
||||
var fileDescriptor_api_17a7876430d97ebd = []byte{
|
||||
// 410 bytes of a gzipped FileDescriptorProto
|
||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x53, 0xc1, 0x6e, 0xd4, 0x30,
|
||||
0x10, 0x55, 0xe2, 0x24, 0x6d, 0x66, 0x11, 0x42, 0x3e, 0x20, 0x53, 0x2a, 0xb4, 0xca, 0x85, 0x15,
|
||||
0x52, 0x13, 0x68, 0x39, 0x20, 0xae, 0xb0, 0x2a, 0xc7, 0xca, 0x7f, 0xe0, 0x6d, 0xac, 0xc4, 0x62,
|
||||
0x13, 0x9b, 0xd8, 0xa9, 0xb4, 0x1f, 0xc7, 0x81, 0xcf, 0xe0, 0x6f, 0x90, 0x27, 0xde, 0xdd, 0xb2,
|
||||
0x5a, 0x2e, 0x74, 0x6f, 0x2f, 0xf6, 0x9b, 0x37, 0x6f, 0xde, 0x38, 0xf0, 0xb6, 0x51, 0xae, 0x1d,
|
||||
0x57, 0xe5, 0xbd, 0xee, 0xaa, 0x4e, 0xdd, 0x0f, 0xba, 0x6a, 0xf4, 0x95, 0x30, 0xaa, 0x32, 0x83,
|
||||
0x76, 0xba, 0x12, 0x46, 0x95, 0x88, 0x68, 0xd6, 0xe8, 0x52, 0x18, 0x55, 0xbc, 0x87, 0xe4, 0x4e,
|
||||
0xa8, 0x81, 0xbe, 0x00, 0xf2, 0x5d, 0x6e, 0x58, 0x34, 0x8f, 0x16, 0x39, 0xf7, 0x90, 0xbe, 0x84,
|
||||
0xec, 0x41, 0xac, 0x47, 0x69, 0x59, 0x3c, 0x27, 0x8b, 0x9c, 0x87, 0xaf, 0xe2, 0x17, 0x81, 0x33,
|
||||
0x2e, 0x7f, 0x8c, 0xd2, 0x3a, 0xcf, 0xe9, 0xa4, 0x6b, 0x75, 0x1d, 0x0a, 0xc3, 0x17, 0xa5, 0x90,
|
||||
0x18, 0xe1, 0x5a, 0x16, 0xe3, 0x29, 0x62, 0x7a, 0x03, 0x59, 0x2b, 0x45, 0x2d, 0x07, 0x46, 0xe6,
|
||||
0x64, 0x31, 0xbb, 0x7e, 0x5d, 0x4e, 0x16, 0xca, 0x20, 0x56, 0x7e, 0xc3, 0xdb, 0x65, 0xef, 0x86,
|
||||
0x0d, 0x0f, 0x54, 0xfa, 0x0e, 0x48, 0x23, 0x1d, 0x4b, 0xb0, 0x82, 0x1d, 0x56, 0xdc, 0x4a, 0x37,
|
||||
0xd1, 0x3d, 0x89, 0x5e, 0x41, 0x62, 0xb4, 0x75, 0x2c, 0x45, 0xf2, 0xab, 0x43, 0xf2, 0x9d, 0xb6,
|
||||
0x81, 0x8d, 0x34, 0xef, 0x71, 0xa5, 0xeb, 0x0d, 0xcb, 0x26, 0x8f, 0x1e, 0xfb, 0x14, 0xc6, 0x61,
|
||||
0xcd, 0xce, 0xa6, 0x14, 0xc6, 0x61, 0x7d, 0x71, 0x0b, 0xb3, 0x47, 0xbe, 0x8e, 0xc4, 0x54, 0x40,
|
||||
0x8a, 0xc1, 0xe0, 0xac, 0xb3, 0xeb, 0x67, 0xdb, 0xb6, 0x3e, 0x55, 0x3e, 0x5d, 0x7d, 0x8e, 0x3f,
|
||||
0x45, 0x17, 0x5f, 0xe1, 0x7c, 0x6b, 0xf7, 0x09, 0x2a, 0x4b, 0xc8, 0x77, 0x73, 0xfc, 0xbf, 0x4c,
|
||||
0xf1, 0x33, 0x82, 0x73, 0x2e, 0xad, 0xd1, 0xbd, 0x95, 0xf4, 0x0d, 0x80, 0x75, 0xc2, 0x8d, 0xf6,
|
||||
0x8b, 0xae, 0x25, 0xaa, 0xa5, 0xfc, 0xd1, 0x09, 0xfd, 0xb8, 0x5b, 0x5c, 0x8c, 0xc9, 0x5e, 0xee,
|
||||
0x93, 0x9d, 0x14, 0x8e, 0x6e, 0x6e, 0x1b, 0x2f, 0xd9, 0xc7, 0x7b, 0xb2, 0x30, 0x8b, 0xdf, 0x11,
|
||||
0xa4, 0xcb, 0x07, 0xd9, 0xe3, 0x16, 0x7b, 0xd1, 0xc9, 0x20, 0x82, 0x98, 0x3e, 0x87, 0x58, 0xd5,
|
||||
0xe1, 0xed, 0xc5, 0xaa, 0xa6, 0x97, 0x90, 0x3b, 0xd5, 0x49, 0xeb, 0x44, 0x67, 0xd0, 0x0f, 0xe1,
|
||||
0xfb, 0x03, 0xfa, 0x61, 0x37, 0x5e, 0xf2, 0xf7, 0xc3, 0xc1, 0x06, 0xff, 0x9a, 0xad, 0x16, 0x4e,
|
||||
0xb0, 0x74, 0x6a, 0xea, 0xf1, 0xc9, 0x66, 0x5b, 0x65, 0xf8, 0x83, 0xde, 0xfc, 0x09, 0x00, 0x00,
|
||||
0xff, 0xff, 0x7a, 0xb4, 0xd4, 0x8f, 0xcb, 0x03, 0x00, 0x00,
|
||||
}
|
43
api/proto/api.proto
Normal file
43
api/proto/api.proto
Normal file
@@ -0,0 +1,43 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package go.api;
|
||||
|
||||
message Pair {
|
||||
string key = 1;
|
||||
repeated string values = 2;
|
||||
}
|
||||
|
||||
// A HTTP request as RPC
|
||||
// Forward by the api handler
|
||||
message Request {
|
||||
string method = 1;
|
||||
string path = 2;
|
||||
map<string, Pair> header = 3;
|
||||
map<string, Pair> get = 4;
|
||||
map<string, Pair> post = 5;
|
||||
string body = 6; // raw request body; if not application/x-www-form-urlencoded
|
||||
string url = 7;
|
||||
}
|
||||
|
||||
// A HTTP response as RPC
|
||||
// Expected response for the api handler
|
||||
message Response {
|
||||
int32 statusCode = 1;
|
||||
map<string, Pair> header = 2;
|
||||
string body = 3;
|
||||
}
|
||||
|
||||
// A HTTP event as RPC
|
||||
// Forwarded by the event handler
|
||||
message Event {
|
||||
// e.g login
|
||||
string name = 1;
|
||||
// uuid
|
||||
string id = 2;
|
||||
// unix timestamp of event
|
||||
int64 timestamp = 3;
|
||||
// event headers
|
||||
map<string, Pair> header = 4;
|
||||
// the event data
|
||||
string data = 5;
|
||||
}
|
38
api/resolver/grpc/grpc.go
Normal file
38
api/resolver/grpc/grpc.go
Normal file
@@ -0,0 +1,38 @@
|
||||
// Package grpc resolves a grpc service like /greeter.Say/Hello to greeter service
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/micro/go-micro/api/resolver"
|
||||
)
|
||||
|
||||
type Resolver struct{}
|
||||
|
||||
func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) {
|
||||
// /foo.Bar/Service
|
||||
if req.URL.Path == "/" {
|
||||
return nil, errors.New("unknown name")
|
||||
}
|
||||
// [foo.Bar, Service]
|
||||
parts := strings.Split(req.URL.Path[1:], "/")
|
||||
// [foo, Bar]
|
||||
name := strings.Split(parts[0], ".")
|
||||
// foo
|
||||
return &resolver.Endpoint{
|
||||
Name: strings.Join(name[:len(name)-1], "."),
|
||||
Host: req.Host,
|
||||
Method: req.Method,
|
||||
Path: req.URL.Path,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Resolver) String() string {
|
||||
return "grpc"
|
||||
}
|
||||
|
||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
||||
return &Resolver{}
|
||||
}
|
27
api/resolver/host/host.go
Normal file
27
api/resolver/host/host.go
Normal file
@@ -0,0 +1,27 @@
|
||||
// Package host resolves using http host
|
||||
package host
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/micro/go-micro/api/resolver"
|
||||
)
|
||||
|
||||
type Resolver struct{}
|
||||
|
||||
func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) {
|
||||
return &resolver.Endpoint{
|
||||
Name: req.Host,
|
||||
Host: req.Host,
|
||||
Method: req.Method,
|
||||
Path: req.URL.Path,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Resolver) String() string {
|
||||
return "host"
|
||||
}
|
||||
|
||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
||||
return &Resolver{}
|
||||
}
|
45
api/resolver/micro/micro.go
Normal file
45
api/resolver/micro/micro.go
Normal file
@@ -0,0 +1,45 @@
|
||||
// Package micro provides a micro rpc resolver which prefixes a namespace
|
||||
package micro
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/micro/go-micro/api/resolver"
|
||||
)
|
||||
|
||||
// default resolver for legacy purposes
|
||||
// it uses proxy routing to resolve names
|
||||
// /foo becomes namespace.foo
|
||||
// /v1/foo becomes namespace.v1.foo
|
||||
type Resolver struct {
|
||||
Options resolver.Options
|
||||
}
|
||||
|
||||
func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) {
|
||||
var name, method string
|
||||
|
||||
switch r.Options.Handler {
|
||||
// internal handlers
|
||||
case "meta", "api", "rpc", "micro":
|
||||
name, method = apiRoute(req.URL.Path)
|
||||
default:
|
||||
method = req.Method
|
||||
name = proxyRoute(req.URL.Path)
|
||||
}
|
||||
|
||||
return &resolver.Endpoint{
|
||||
Name: name,
|
||||
Method: method,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Resolver) String() string {
|
||||
return "micro"
|
||||
}
|
||||
|
||||
// NewResolver creates a new micro resolver
|
||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
||||
return &Resolver{
|
||||
Options: resolver.NewOptions(opts...),
|
||||
}
|
||||
}
|
90
api/resolver/micro/route.go
Normal file
90
api/resolver/micro/route.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package micro
|
||||
|
||||
import (
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
proxyRe = regexp.MustCompile("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$")
|
||||
versionRe = regexp.MustCompilePOSIX("^v[0-9]+$")
|
||||
)
|
||||
|
||||
// Translates /foo/bar/zool into api service go.micro.api.foo method Bar.Zool
|
||||
// Translates /foo/bar into api service go.micro.api.foo method Foo.Bar
|
||||
func apiRoute(p string) (string, string) {
|
||||
p = path.Clean(p)
|
||||
p = strings.TrimPrefix(p, "/")
|
||||
parts := strings.Split(p, "/")
|
||||
|
||||
// If we've got two or less parts
|
||||
// Use first part as service
|
||||
// Use all parts as method
|
||||
if len(parts) <= 2 {
|
||||
name := parts[0]
|
||||
return name, methodName(parts)
|
||||
}
|
||||
|
||||
// Treat /v[0-9]+ as versioning where we have 3 parts
|
||||
// /v1/foo/bar => service: v1.foo method: Foo.bar
|
||||
if len(parts) == 3 && versionRe.Match([]byte(parts[0])) {
|
||||
name := strings.Join(parts[:len(parts)-1], ".")
|
||||
return name, methodName(parts[len(parts)-2:])
|
||||
}
|
||||
|
||||
// Service is everything minus last two parts
|
||||
// Method is the last two parts
|
||||
name := strings.Join(parts[:len(parts)-2], ".")
|
||||
return name, methodName(parts[len(parts)-2:])
|
||||
}
|
||||
|
||||
func proxyRoute(p string) string {
|
||||
parts := strings.Split(p, "/")
|
||||
if len(parts) < 2 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var service string
|
||||
var alias string
|
||||
|
||||
// /[service]/methods
|
||||
if len(parts) > 2 {
|
||||
// /v1/[service]
|
||||
if versionRe.MatchString(parts[1]) {
|
||||
service = parts[1] + "." + parts[2]
|
||||
alias = parts[2]
|
||||
} else {
|
||||
service = parts[1]
|
||||
alias = parts[1]
|
||||
}
|
||||
// /[service]
|
||||
} else {
|
||||
service = parts[1]
|
||||
alias = parts[1]
|
||||
}
|
||||
|
||||
// check service name is valid
|
||||
if !proxyRe.MatchString(alias) {
|
||||
return ""
|
||||
}
|
||||
|
||||
return service
|
||||
}
|
||||
|
||||
func methodName(parts []string) string {
|
||||
for i, part := range parts {
|
||||
parts[i] = toCamel(part)
|
||||
}
|
||||
|
||||
return strings.Join(parts, ".")
|
||||
}
|
||||
|
||||
func toCamel(s string) string {
|
||||
words := strings.Split(s, "-")
|
||||
var out string
|
||||
for _, word := range words {
|
||||
out += strings.Title(word)
|
||||
}
|
||||
return out
|
||||
}
|
130
api/resolver/micro/route_test.go
Normal file
130
api/resolver/micro/route_test.go
Normal file
@@ -0,0 +1,130 @@
|
||||
package micro
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestApiRoute(t *testing.T) {
|
||||
testData := []struct {
|
||||
path string
|
||||
service string
|
||||
method string
|
||||
}{
|
||||
{
|
||||
"/foo/bar",
|
||||
"foo",
|
||||
"Foo.Bar",
|
||||
},
|
||||
{
|
||||
"/foo/foo/bar",
|
||||
"foo",
|
||||
"Foo.Bar",
|
||||
},
|
||||
{
|
||||
"/foo/bar/baz",
|
||||
"foo",
|
||||
"Bar.Baz",
|
||||
},
|
||||
{
|
||||
"/foo/bar/baz-xyz",
|
||||
"foo",
|
||||
"Bar.BazXyz",
|
||||
},
|
||||
{
|
||||
"/foo/bar/baz/cat",
|
||||
"foo.bar",
|
||||
"Baz.Cat",
|
||||
},
|
||||
{
|
||||
"/foo/bar/baz/cat/car",
|
||||
"foo.bar.baz",
|
||||
"Cat.Car",
|
||||
},
|
||||
{
|
||||
"/foo/fooBar/bazCat",
|
||||
"foo",
|
||||
"FooBar.BazCat",
|
||||
},
|
||||
{
|
||||
"/v1/foo/bar",
|
||||
"v1.foo",
|
||||
"Foo.Bar",
|
||||
},
|
||||
{
|
||||
"/v1/foo/bar/baz",
|
||||
"v1.foo",
|
||||
"Bar.Baz",
|
||||
},
|
||||
{
|
||||
"/v1/foo/bar/baz/cat",
|
||||
"v1.foo.bar",
|
||||
"Baz.Cat",
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range testData {
|
||||
s, m := apiRoute(d.path)
|
||||
if d.service != s {
|
||||
t.Fatalf("Expected service: %s for path: %s got: %s %s", d.service, d.path, s, m)
|
||||
}
|
||||
if d.method != m {
|
||||
t.Fatalf("Expected service: %s for path: %s got: %s", d.method, d.path, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyRoute(t *testing.T) {
|
||||
testData := []struct {
|
||||
path string
|
||||
service string
|
||||
}{
|
||||
// no namespace
|
||||
{
|
||||
"/f",
|
||||
"f",
|
||||
},
|
||||
{
|
||||
"/f",
|
||||
"f",
|
||||
},
|
||||
{
|
||||
"/f-b",
|
||||
"f-b",
|
||||
},
|
||||
{
|
||||
"/foo/bar",
|
||||
"foo",
|
||||
},
|
||||
{
|
||||
"/foo-bar",
|
||||
"foo-bar",
|
||||
},
|
||||
{
|
||||
"/foo-bar-baz",
|
||||
"foo-bar-baz",
|
||||
},
|
||||
{
|
||||
"/foo/bar/bar",
|
||||
"foo",
|
||||
},
|
||||
{
|
||||
"/v1/foo/bar",
|
||||
"v1.foo",
|
||||
},
|
||||
{
|
||||
"/v1/foo/bar/baz",
|
||||
"v1.foo",
|
||||
},
|
||||
{
|
||||
"/v1/foo/bar/baz/cat",
|
||||
"v1.foo",
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range testData {
|
||||
s := proxyRoute(d.path)
|
||||
if d.service != s {
|
||||
t.Fatalf("Expected service: %s for path: %s got: %s", d.service, d.path, s)
|
||||
}
|
||||
}
|
||||
}
|
24
api/resolver/options.go
Normal file
24
api/resolver/options.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package resolver
|
||||
|
||||
// NewOptions returns new initialised options
|
||||
func NewOptions(opts ...Option) Options {
|
||||
var options Options
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
// WithHandler sets the handler being used
|
||||
func WithHandler(h string) Option {
|
||||
return func(o *Options) {
|
||||
o.Handler = h
|
||||
}
|
||||
}
|
||||
|
||||
// WithNamespace sets the namespace being used
|
||||
func WithNamespace(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Namespace = n
|
||||
}
|
||||
}
|
33
api/resolver/path/path.go
Normal file
33
api/resolver/path/path.go
Normal file
@@ -0,0 +1,33 @@
|
||||
// Package path resolves using http path
|
||||
package path
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/micro/go-micro/api/resolver"
|
||||
)
|
||||
|
||||
type Resolver struct{}
|
||||
|
||||
func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) {
|
||||
if req.URL.Path == "/" {
|
||||
return nil, errors.New("unknown name")
|
||||
}
|
||||
parts := strings.Split(req.URL.Path[1:], "/")
|
||||
return &resolver.Endpoint{
|
||||
Name: parts[0],
|
||||
Host: req.Host,
|
||||
Method: req.Method,
|
||||
Path: req.URL.Path,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Resolver) String() string {
|
||||
return "path"
|
||||
}
|
||||
|
||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
||||
return &Resolver{}
|
||||
}
|
31
api/resolver/resolver.go
Normal file
31
api/resolver/resolver.go
Normal file
@@ -0,0 +1,31 @@
|
||||
// Package resolver resolves a http request to an endpoint
|
||||
package resolver
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Resolver resolves requests to endpoints
|
||||
type Resolver interface {
|
||||
Resolve(r *http.Request) (*Endpoint, error)
|
||||
String() string
|
||||
}
|
||||
|
||||
// Endpoint is the endpoint for a http request
|
||||
type Endpoint struct {
|
||||
// e.g greeter
|
||||
Name string
|
||||
// HTTP Host e.g example.com
|
||||
Host string
|
||||
// HTTP Methods e.g GET, POST
|
||||
Method string
|
||||
// HTTP Path e.g /greeter.
|
||||
Path string
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Handler string
|
||||
Namespace string
|
||||
}
|
||||
|
||||
type Option func(o *Options)
|
59
api/resolver/vpath/vpath.go
Normal file
59
api/resolver/vpath/vpath.go
Normal file
@@ -0,0 +1,59 @@
|
||||
// Package vpath resolves using http path and recognised versioned urls
|
||||
package vpath
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/micro/go-micro/api/resolver"
|
||||
)
|
||||
|
||||
type Resolver struct{}
|
||||
|
||||
var (
|
||||
re = regexp.MustCompile("^v[0-9]+$")
|
||||
)
|
||||
|
||||
func (r *Resolver) Resolve(req *http.Request) (*resolver.Endpoint, error) {
|
||||
if req.URL.Path == "/" {
|
||||
return nil, errors.New("unknown name")
|
||||
}
|
||||
|
||||
parts := strings.Split(req.URL.Path[1:], "/")
|
||||
|
||||
if len(parts) == 1 {
|
||||
return &resolver.Endpoint{
|
||||
Name: parts[0],
|
||||
Host: req.Host,
|
||||
Method: req.Method,
|
||||
Path: req.URL.Path,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// /v1/foo
|
||||
if re.MatchString(parts[0]) {
|
||||
return &resolver.Endpoint{
|
||||
Name: parts[1],
|
||||
Host: req.Host,
|
||||
Method: req.Method,
|
||||
Path: req.URL.Path,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &resolver.Endpoint{
|
||||
Name: parts[0],
|
||||
Host: req.Host,
|
||||
Method: req.Method,
|
||||
Path: req.URL.Path,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Resolver) String() string {
|
||||
return "path"
|
||||
}
|
||||
|
||||
func NewResolver(opts ...resolver.Option) resolver.Resolver {
|
||||
return &Resolver{}
|
||||
}
|
61
api/router/options.go
Normal file
61
api/router/options.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/micro/go-micro/api/resolver"
|
||||
"github.com/micro/go-micro/api/resolver/micro"
|
||||
"github.com/micro/go-micro/cmd"
|
||||
"github.com/micro/go-micro/registry"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
Namespace string
|
||||
Handler string
|
||||
Registry registry.Registry
|
||||
Resolver resolver.Resolver
|
||||
}
|
||||
|
||||
type Option func(o *Options)
|
||||
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Handler: "meta",
|
||||
Registry: *cmd.DefaultOptions().Registry,
|
||||
}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
if options.Resolver == nil {
|
||||
options.Resolver = micro.NewResolver(
|
||||
resolver.WithHandler(options.Handler),
|
||||
resolver.WithNamespace(options.Namespace),
|
||||
)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
func WithHandler(h string) Option {
|
||||
return func(o *Options) {
|
||||
o.Handler = h
|
||||
}
|
||||
}
|
||||
|
||||
func WithNamespace(ns string) Option {
|
||||
return func(o *Options) {
|
||||
o.Namespace = ns
|
||||
}
|
||||
}
|
||||
|
||||
func WithRegistry(r registry.Registry) Option {
|
||||
return func(o *Options) {
|
||||
o.Registry = r
|
||||
}
|
||||
}
|
||||
|
||||
func WithResolver(r resolver.Resolver) Option {
|
||||
return func(o *Options) {
|
||||
o.Resolver = r
|
||||
}
|
||||
}
|
393
api/router/registry/registry.go
Normal file
393
api/router/registry/registry.go
Normal file
@@ -0,0 +1,393 @@
|
||||
// Package registry provides a dynamic api service router
|
||||
package registry
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/micro/go-micro/api"
|
||||
"github.com/micro/go-micro/api/router"
|
||||
"github.com/micro/go-micro/registry"
|
||||
"github.com/micro/go-micro/registry/cache"
|
||||
)
|
||||
|
||||
// router is the default router
|
||||
type registryRouter struct {
|
||||
exit chan bool
|
||||
opts router.Options
|
||||
|
||||
// registry cache
|
||||
rc cache.Cache
|
||||
|
||||
sync.RWMutex
|
||||
eps map[string]*api.Service
|
||||
}
|
||||
|
||||
func setNamespace(ns, name string) string {
|
||||
ns = strings.TrimSpace(ns)
|
||||
name = strings.TrimSpace(name)
|
||||
|
||||
// no namespace
|
||||
if len(ns) == 0 {
|
||||
return name
|
||||
}
|
||||
|
||||
switch {
|
||||
// has - suffix
|
||||
case strings.HasSuffix(ns, "-"):
|
||||
return strings.Replace(ns+name, ".", "-", -1)
|
||||
// has . suffix
|
||||
case strings.HasSuffix(ns, "."):
|
||||
return ns + name
|
||||
}
|
||||
|
||||
// default join .
|
||||
return strings.Join([]string{ns, name}, ".")
|
||||
}
|
||||
|
||||
func (r *registryRouter) isClosed() bool {
|
||||
select {
|
||||
case <-r.exit:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// refresh list of api services
|
||||
func (r *registryRouter) refresh() {
|
||||
var attempts int
|
||||
|
||||
for {
|
||||
services, err := r.opts.Registry.ListServices()
|
||||
if err != nil {
|
||||
attempts++
|
||||
log.Println("Error listing endpoints", err)
|
||||
time.Sleep(time.Duration(attempts) * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
attempts = 0
|
||||
|
||||
// for each service, get service and store endpoints
|
||||
for _, s := range services {
|
||||
// only get services for this namespace
|
||||
if !strings.HasPrefix(s.Name, r.opts.Namespace) {
|
||||
continue
|
||||
}
|
||||
service, err := r.rc.GetService(s.Name)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
r.store(service)
|
||||
}
|
||||
|
||||
// refresh list in 10 minutes... cruft
|
||||
select {
|
||||
case <-time.After(time.Minute * 10):
|
||||
case <-r.exit:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// process watch event
|
||||
func (r *registryRouter) process(res *registry.Result) {
|
||||
// skip these things
|
||||
if res == nil || res.Service == nil || !strings.HasPrefix(res.Service.Name, r.opts.Namespace) {
|
||||
return
|
||||
}
|
||||
|
||||
// get entry from cache
|
||||
service, err := r.rc.GetService(res.Service.Name)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// update our local endpoints
|
||||
r.store(service)
|
||||
}
|
||||
|
||||
// store local endpoint cache
|
||||
func (r *registryRouter) store(services []*registry.Service) {
|
||||
// endpoints
|
||||
eps := map[string]*api.Service{}
|
||||
|
||||
// services
|
||||
names := map[string]bool{}
|
||||
|
||||
// create a new endpoint mapping
|
||||
for _, service := range services {
|
||||
// set names we need later
|
||||
names[service.Name] = true
|
||||
|
||||
// map per endpoint
|
||||
for _, endpoint := range service.Endpoints {
|
||||
// create a key service:endpoint_name
|
||||
key := fmt.Sprintf("%s:%s", service.Name, endpoint.Name)
|
||||
// decode endpoint
|
||||
end := api.Decode(endpoint.Metadata)
|
||||
|
||||
// if we got nothing skip
|
||||
if err := api.Validate(end); err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// try get endpoint
|
||||
ep, ok := eps[key]
|
||||
if !ok {
|
||||
ep = &api.Service{Name: service.Name}
|
||||
}
|
||||
|
||||
// overwrite the endpoint
|
||||
ep.Endpoint = end
|
||||
// append services
|
||||
ep.Services = append(ep.Services, service)
|
||||
// store it
|
||||
eps[key] = ep
|
||||
}
|
||||
}
|
||||
|
||||
r.Lock()
|
||||
defer r.Unlock()
|
||||
|
||||
// delete any existing eps for services we know
|
||||
for key, service := range r.eps {
|
||||
// skip what we don't care about
|
||||
if !names[service.Name] {
|
||||
continue
|
||||
}
|
||||
|
||||
// ok we know this thing
|
||||
// delete delete delete
|
||||
delete(r.eps, key)
|
||||
}
|
||||
|
||||
// now set the eps we have
|
||||
for name, endpoint := range eps {
|
||||
r.eps[name] = endpoint
|
||||
}
|
||||
}
|
||||
|
||||
// watch for endpoint changes
|
||||
func (r *registryRouter) watch() {
|
||||
var attempts int
|
||||
|
||||
for {
|
||||
if r.isClosed() {
|
||||
return
|
||||
}
|
||||
|
||||
// watch for changes
|
||||
w, err := r.opts.Registry.Watch()
|
||||
if err != nil {
|
||||
attempts++
|
||||
log.Println("Error watching endpoints", err)
|
||||
time.Sleep(time.Duration(attempts) * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
ch := make(chan bool)
|
||||
|
||||
go func() {
|
||||
select {
|
||||
case <-ch:
|
||||
w.Stop()
|
||||
case <-r.exit:
|
||||
w.Stop()
|
||||
}
|
||||
}()
|
||||
|
||||
// reset if we get here
|
||||
attempts = 0
|
||||
|
||||
for {
|
||||
// process next event
|
||||
res, err := w.Next()
|
||||
if err != nil {
|
||||
log.Println("Error getting next endpoint", err)
|
||||
close(ch)
|
||||
break
|
||||
}
|
||||
r.process(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *registryRouter) Options() router.Options {
|
||||
return r.opts
|
||||
}
|
||||
|
||||
func (r *registryRouter) Close() error {
|
||||
select {
|
||||
case <-r.exit:
|
||||
return nil
|
||||
default:
|
||||
close(r.exit)
|
||||
r.rc.Stop()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *registryRouter) Endpoint(req *http.Request) (*api.Service, error) {
|
||||
if r.isClosed() {
|
||||
return nil, errors.New("router closed")
|
||||
}
|
||||
|
||||
r.RLock()
|
||||
defer r.RUnlock()
|
||||
|
||||
// use the first match
|
||||
// TODO: weighted matching
|
||||
for _, e := range r.eps {
|
||||
ep := e.Endpoint
|
||||
|
||||
// match
|
||||
var pathMatch, hostMatch, methodMatch bool
|
||||
|
||||
// 1. try method GET, POST, PUT, etc
|
||||
// 2. try host example.com, foobar.com, etc
|
||||
// 3. try path /foo/bar, /bar/baz, etc
|
||||
|
||||
// 1. try match method
|
||||
for _, m := range ep.Method {
|
||||
if req.Method == m {
|
||||
methodMatch = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// no match on method pass
|
||||
if len(ep.Method) > 0 && !methodMatch {
|
||||
continue
|
||||
}
|
||||
|
||||
// 2. try match host
|
||||
for _, h := range ep.Host {
|
||||
if req.Host == h {
|
||||
hostMatch = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// no match on host pass
|
||||
if len(ep.Host) > 0 && !hostMatch {
|
||||
continue
|
||||
}
|
||||
|
||||
// 3. try match paths
|
||||
for _, p := range ep.Path {
|
||||
re, err := regexp.CompilePOSIX(p)
|
||||
if err == nil && re.MatchString(req.URL.Path) {
|
||||
pathMatch = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// no match pass
|
||||
if len(ep.Path) > 0 && !pathMatch {
|
||||
continue
|
||||
}
|
||||
|
||||
// TODO: Percentage traffic
|
||||
|
||||
// we got here, so its a match
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// no match
|
||||
return nil, errors.New("not found")
|
||||
}
|
||||
|
||||
func (r *registryRouter) Route(req *http.Request) (*api.Service, error) {
|
||||
if r.isClosed() {
|
||||
return nil, errors.New("router closed")
|
||||
}
|
||||
|
||||
// try get an endpoint
|
||||
ep, err := r.Endpoint(req)
|
||||
if err == nil {
|
||||
return ep, nil
|
||||
}
|
||||
|
||||
// error not nil
|
||||
// ignore that shit
|
||||
// TODO: don't ignore that shit
|
||||
|
||||
// get the service name
|
||||
rp, err := r.opts.Resolver.Resolve(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// service name
|
||||
name := setNamespace(r.opts.Namespace, rp.Name)
|
||||
|
||||
// get service
|
||||
services, err := r.rc.GetService(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// only use endpoint matching when the meta handler is set aka api.Default
|
||||
switch r.opts.Handler {
|
||||
// rpc handlers
|
||||
case "meta", "api", "rpc":
|
||||
handler := r.opts.Handler
|
||||
|
||||
// set default handler to api
|
||||
if r.opts.Handler == "meta" {
|
||||
handler = "rpc"
|
||||
}
|
||||
|
||||
// construct api service
|
||||
return &api.Service{
|
||||
Name: name,
|
||||
Endpoint: &api.Endpoint{
|
||||
Name: rp.Method,
|
||||
Handler: handler,
|
||||
},
|
||||
Services: services,
|
||||
}, nil
|
||||
// http handler
|
||||
case "http", "proxy", "web":
|
||||
// construct api service
|
||||
return &api.Service{
|
||||
Name: name,
|
||||
Endpoint: &api.Endpoint{
|
||||
Name: req.URL.String(),
|
||||
Handler: r.opts.Handler,
|
||||
Host: []string{req.Host},
|
||||
Method: []string{req.Method},
|
||||
Path: []string{req.URL.Path},
|
||||
},
|
||||
Services: services,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, errors.New("unknown handler")
|
||||
}
|
||||
|
||||
func newRouter(opts ...router.Option) *registryRouter {
|
||||
options := router.NewOptions(opts...)
|
||||
r := ®istryRouter{
|
||||
exit: make(chan bool),
|
||||
opts: options,
|
||||
rc: cache.New(options.Registry),
|
||||
eps: make(map[string]*api.Service),
|
||||
}
|
||||
go r.watch()
|
||||
go r.refresh()
|
||||
return r
|
||||
}
|
||||
|
||||
// NewRouter returns the default router
|
||||
func NewRouter(opts ...router.Option) router.Router {
|
||||
return newRouter(opts...)
|
||||
}
|
181
api/router/registry/registry_test.go
Normal file
181
api/router/registry/registry_test.go
Normal file
@@ -0,0 +1,181 @@
|
||||
package registry
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/micro/go-micro/api"
|
||||
)
|
||||
|
||||
func TestSetNamespace(t *testing.T) {
|
||||
testCases := []struct {
|
||||
namespace string
|
||||
name string
|
||||
expected string
|
||||
}{
|
||||
// default dotted path
|
||||
{
|
||||
"go.micro.api",
|
||||
"foo",
|
||||
"go.micro.api.foo",
|
||||
},
|
||||
// dotted end
|
||||
{
|
||||
"go.micro.api.",
|
||||
"foo",
|
||||
"go.micro.api.foo",
|
||||
},
|
||||
// dashed end
|
||||
{
|
||||
"go-micro-api-",
|
||||
"foo",
|
||||
"go-micro-api-foo",
|
||||
},
|
||||
// no namespace
|
||||
{
|
||||
"",
|
||||
"foo",
|
||||
"foo",
|
||||
},
|
||||
{
|
||||
"go-micro-api-",
|
||||
"v2.foo",
|
||||
"go-micro-api-v2-foo",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
name := setNamespace(test.namespace, test.name)
|
||||
if name != test.expected {
|
||||
t.Fatalf("expected name %s got %s", test.expected, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouter(t *testing.T) {
|
||||
r := newRouter()
|
||||
|
||||
compare := func(expect, got []string) bool {
|
||||
// no data to compare, return true
|
||||
if len(expect) == 0 && len(got) == 0 {
|
||||
return true
|
||||
}
|
||||
// no data expected but got some return false
|
||||
if len(expect) == 0 && len(got) > 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
// compare expected with what we got
|
||||
for _, e := range expect {
|
||||
var seen bool
|
||||
for _, g := range got {
|
||||
if e == g {
|
||||
seen = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !seen {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// we're done, return true
|
||||
return true
|
||||
}
|
||||
|
||||
testData := []struct {
|
||||
e *api.Endpoint
|
||||
r *http.Request
|
||||
m bool
|
||||
}{
|
||||
{
|
||||
e: &api.Endpoint{
|
||||
Name: "Foo.Bar",
|
||||
Host: []string{"example.com"},
|
||||
Method: []string{"GET"},
|
||||
Path: []string{"/foo"},
|
||||
},
|
||||
r: &http.Request{
|
||||
Host: "example.com",
|
||||
Method: "GET",
|
||||
URL: &url.URL{
|
||||
Path: "/foo",
|
||||
},
|
||||
},
|
||||
m: true,
|
||||
},
|
||||
{
|
||||
e: &api.Endpoint{
|
||||
Name: "Bar.Baz",
|
||||
Host: []string{"example.com", "foo.com"},
|
||||
Method: []string{"GET", "POST"},
|
||||
Path: []string{"/foo/bar"},
|
||||
},
|
||||
r: &http.Request{
|
||||
Host: "foo.com",
|
||||
Method: "POST",
|
||||
URL: &url.URL{
|
||||
Path: "/foo/bar",
|
||||
},
|
||||
},
|
||||
m: true,
|
||||
},
|
||||
{
|
||||
e: &api.Endpoint{
|
||||
Name: "Test.Cruft",
|
||||
Host: []string{"example.com", "foo.com"},
|
||||
Method: []string{"GET", "POST"},
|
||||
Path: []string{"/xyz"},
|
||||
},
|
||||
r: &http.Request{
|
||||
Host: "fail.com",
|
||||
Method: "DELETE",
|
||||
URL: &url.URL{
|
||||
Path: "/test/fail",
|
||||
},
|
||||
},
|
||||
m: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range testData {
|
||||
key := fmt.Sprintf("%s:%s", "test.service", d.e.Name)
|
||||
r.eps[key] = &api.Service{
|
||||
Endpoint: d.e,
|
||||
}
|
||||
}
|
||||
|
||||
for _, d := range testData {
|
||||
e, err := r.Endpoint(d.r)
|
||||
if d.m && err != nil {
|
||||
t.Fatalf("expected match, got %v", err)
|
||||
}
|
||||
if !d.m && err == nil {
|
||||
t.Fatal("expected error got match")
|
||||
}
|
||||
// skip testing the non match
|
||||
if !d.m {
|
||||
continue
|
||||
}
|
||||
|
||||
ep := e.Endpoint
|
||||
|
||||
// test the match
|
||||
if d.e.Name != ep.Name {
|
||||
t.Fatalf("expected %v got %v", d.e.Name, ep.Name)
|
||||
}
|
||||
if ok := compare(d.e.Method, ep.Method); !ok {
|
||||
t.Fatalf("expected %v got %v", d.e.Method, ep.Method)
|
||||
}
|
||||
if ok := compare(d.e.Path, ep.Path); !ok {
|
||||
t.Fatalf("expected %v got %v", d.e.Path, ep.Path)
|
||||
}
|
||||
if ok := compare(d.e.Host, ep.Host); !ok {
|
||||
t.Fatalf("expected %v got %v", d.e.Host, ep.Host)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
20
api/router/router.go
Normal file
20
api/router/router.go
Normal file
@@ -0,0 +1,20 @@
|
||||
// Package router provides api service routing
|
||||
package router
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/micro/go-micro/api"
|
||||
)
|
||||
|
||||
// Router is used to determine an endpoint for a request
|
||||
type Router interface {
|
||||
// Returns options
|
||||
Options() Options
|
||||
// Stop the router
|
||||
Close() error
|
||||
// Endpoint returns an api.Service endpoint or an error if it does not exist
|
||||
Endpoint(r *http.Request) (*api.Service, error)
|
||||
// Route returns an api.Service route
|
||||
Route(r *http.Request) (*api.Service, error)
|
||||
}
|
98
api/server/http/http.go
Normal file
98
api/server/http/http.go
Normal file
@@ -0,0 +1,98 @@
|
||||
// Package http provides a http server with features; acme, cors, etc
|
||||
package http
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/gorilla/handlers"
|
||||
"github.com/micro/go-micro/api/server"
|
||||
"github.com/micro/go-micro/util/log"
|
||||
"golang.org/x/crypto/acme/autocert"
|
||||
)
|
||||
|
||||
type httpServer struct {
|
||||
mux *http.ServeMux
|
||||
opts server.Options
|
||||
|
||||
mtx sync.RWMutex
|
||||
address string
|
||||
exit chan chan error
|
||||
}
|
||||
|
||||
func NewServer(address string) server.Server {
|
||||
return &httpServer{
|
||||
opts: server.Options{},
|
||||
mux: http.NewServeMux(),
|
||||
address: address,
|
||||
exit: make(chan chan error),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *httpServer) Address() string {
|
||||
s.mtx.RLock()
|
||||
defer s.mtx.RUnlock()
|
||||
return s.address
|
||||
}
|
||||
|
||||
func (s *httpServer) Init(opts ...server.Option) error {
|
||||
for _, o := range opts {
|
||||
o(&s.opts)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *httpServer) Handle(path string, handler http.Handler) {
|
||||
s.mux.Handle(path, handlers.CombinedLoggingHandler(os.Stdout, handler))
|
||||
}
|
||||
|
||||
func (s *httpServer) Start() error {
|
||||
var l net.Listener
|
||||
var err error
|
||||
|
||||
if s.opts.EnableACME {
|
||||
// should we check the address to make sure its using :443?
|
||||
l = autocert.NewListener(s.opts.ACMEHosts...)
|
||||
} else if s.opts.EnableTLS && s.opts.TLSConfig != nil {
|
||||
l, err = tls.Listen("tcp", s.address, s.opts.TLSConfig)
|
||||
} else {
|
||||
// otherwise plain listen
|
||||
l, err = net.Listen("tcp", s.address)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Logf("HTTP API Listening on %s", l.Addr().String())
|
||||
|
||||
s.mtx.Lock()
|
||||
s.address = l.Addr().String()
|
||||
s.mtx.Unlock()
|
||||
|
||||
go func() {
|
||||
if err := http.Serve(l, s.mux); err != nil {
|
||||
// temporary fix
|
||||
//log.Fatal(err)
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
ch := <-s.exit
|
||||
ch <- l.Close()
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *httpServer) Stop() error {
|
||||
ch := make(chan error)
|
||||
s.exit <- ch
|
||||
return <-ch
|
||||
}
|
||||
|
||||
func (s *httpServer) String() string {
|
||||
return "http"
|
||||
}
|
41
api/server/http/http_test.go
Normal file
41
api/server/http/http_test.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHTTPServer(t *testing.T) {
|
||||
testResponse := "hello world"
|
||||
|
||||
s := NewServer("localhost:0")
|
||||
|
||||
s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, testResponse)
|
||||
}))
|
||||
|
||||
if err := s.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rsp, err := http.Get(fmt.Sprintf("http://%s/", s.Address()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rsp.Body.Close()
|
||||
|
||||
b, err := ioutil.ReadAll(rsp.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if string(b) != testResponse {
|
||||
t.Fatalf("Unexpected response, got %s, expected %s", string(b), testResponse)
|
||||
}
|
||||
|
||||
if err := s.Stop(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
38
api/server/options.go
Normal file
38
api/server/options.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
)
|
||||
|
||||
type Option func(o *Options)
|
||||
|
||||
type Options struct {
|
||||
EnableACME bool
|
||||
EnableTLS bool
|
||||
ACMEHosts []string
|
||||
TLSConfig *tls.Config
|
||||
}
|
||||
|
||||
func ACMEHosts(hosts ...string) Option {
|
||||
return func(o *Options) {
|
||||
o.ACMEHosts = hosts
|
||||
}
|
||||
}
|
||||
|
||||
func EnableACME(b bool) Option {
|
||||
return func(o *Options) {
|
||||
o.EnableACME = b
|
||||
}
|
||||
}
|
||||
|
||||
func EnableTLS(b bool) Option {
|
||||
return func(o *Options) {
|
||||
o.EnableTLS = b
|
||||
}
|
||||
}
|
||||
|
||||
func TLSConfig(t *tls.Config) Option {
|
||||
return func(o *Options) {
|
||||
o.TLSConfig = t
|
||||
}
|
||||
}
|
15
api/server/server.go
Normal file
15
api/server/server.go
Normal file
@@ -0,0 +1,15 @@
|
||||
// Package server provides an API gateway server which handles inbound requests
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Server serves api requests
|
||||
type Server interface {
|
||||
Address() string
|
||||
Init(opts ...Option) error
|
||||
Handle(path string, handler http.Handler)
|
||||
Start() error
|
||||
Stop() error
|
||||
}
|
Reference in New Issue
Block a user