Skip to content

Commit

Permalink
First
Browse files Browse the repository at this point in the history
  • Loading branch information
Asim committed Jan 13, 2015
0 parents commit 8e55cde
Show file tree
Hide file tree
Showing 43 changed files with 1,639 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.me
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Go Micro - a microservices client/server library

This a minimalistic step into microservices using HTTP/RPC and protobuf.
13 changes: 13 additions & 0 deletions client/buffer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package client

import (
"io"
)

type buffer struct {
io.ReadWriter
}

func (b *buffer) Close() error {
return nil
}
33 changes: 33 additions & 0 deletions client/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package client

type Client interface {
NewRequest(string, string, interface{}) Request
NewProtoRequest(string, string, interface{}) Request
NewJsonRequest(string, string, interface{}) Request
Call(interface{}, interface{}) error
CallRemote(string, string, interface{}, interface{}) error
}

var (
client = NewRpcClient()
)

func Call(request Request, response interface{}) error {
return client.Call(request, response)
}

func CallRemote(address, path string, request Request, response interface{}) error {
return client.CallRemote(address, path, request, response)
}

func NewRequest(service, method string, request interface{}) Request {
return client.NewRequest(service, method, request)
}

func NewProtoRequest(service, method string, request interface{}) Request {
return client.NewProtoRequest(service, method, request)
}

func NewJsonRequest(service, method string, request interface{}) Request {
return client.NewJsonRequest(service, method, request)
}
8 changes: 8 additions & 0 deletions client/headers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package client

type Headers interface {
Add(string, string)
Del(string)
Get(string) string
Set(string, string)
}
9 changes: 9 additions & 0 deletions client/request.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package client

type Request interface {
Service() string
Method() string
ContentType() string
Request() interface{}
Headers() Headers
}
157 changes: 157 additions & 0 deletions client/rpc_client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
package client

import (
"bytes"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"time"

"github.com/asim/go-micro/errors"
"github.com/asim/go-micro/registry"
rpc "github.com/youtube/vitess/go/rpcplus"
js "github.com/youtube/vitess/go/rpcplus/jsonrpc"
pb "github.com/youtube/vitess/go/rpcplus/pbrpc"
)

type headerRoundTripper struct {
r http.RoundTripper
}

type RpcClient struct{}

func init() {
rand.Seed(time.Now().UnixNano())
}

func (t *headerRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
r.Header.Set("X-Client-Version", "1.0")
return t.r.RoundTrip(r)
}

func (r *RpcClient) call(address, path string, request Request, response interface{}) error {
pReq := &rpc.Request{
ServiceMethod: request.Method(),
}

reqB := bytes.NewBuffer(nil)
defer reqB.Reset()
buf := &buffer{
reqB,
}

var cc rpc.ClientCodec
switch request.ContentType() {
case "application/octet-stream":
cc = pb.NewClientCodec(buf)
case "application/json":
cc = js.NewClientCodec(buf)
default:
return errors.InternalServerError("go.micro.client", fmt.Sprintf("Unsupported request type: %s", request.ContentType()))
}

err := cc.WriteRequest(pReq, request.Request())
if err != nil {
return errors.InternalServerError("go.micro.client", fmt.Sprintf("Error writing request: %v", err))
}

client := &http.Client{}
client.Transport = &headerRoundTripper{http.DefaultTransport}

request.Headers().Set("Content-Type", request.ContentType())

hreq := &http.Request{
Method: "POST",
URL: &url.URL{
Scheme: "http",
Host: address,
Path: path,
},
Header: request.Headers().(http.Header),
Body: buf,
ContentLength: int64(reqB.Len()),
Host: address,
}

rsp, err := client.Do(hreq)
if err != nil {
return errors.InternalServerError("go.micro.client", fmt.Sprintf("Error sending request: %v", err))
}
defer rsp.Body.Close()

b, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return errors.InternalServerError("go.micro.client", fmt.Sprintf("Error reading response: %v", err))
}

rspB := bytes.NewBuffer(b)
defer rspB.Reset()
rBuf := &buffer{
rspB,
}

switch rsp.Header.Get("Content-Type") {
case "application/octet-stream":
cc = pb.NewClientCodec(rBuf)
case "application/json":
cc = js.NewClientCodec(rBuf)
default:
return errors.InternalServerError("go.micro.client", string(b))
}

pRsp := &rpc.Response{}
err = cc.ReadResponseHeader(pRsp)
if err != nil {
return errors.InternalServerError("go.micro.client", fmt.Sprintf("Error reading response headers: %v", err))
}

if len(pRsp.Error) > 0 {
return errors.Parse(pRsp.Error)
}

err = cc.ReadResponseBody(response)
if err != nil {
return errors.InternalServerError("go.micro.client", fmt.Sprintf("Error reading response body: %v", err))
}

return nil
}

func (r *RpcClient) CallRemote(address, path string, request Request, response interface{}) error {
return r.call(address, path, request, response)
}

// TODO: Call(..., opts *Options) error {
func (r *RpcClient) Call(request Request, response interface{}) error {
service, err := registry.GetService(request.Service())
if err != nil {
return errors.InternalServerError("go.micro.client", err.Error())
}

if len(service.Nodes()) == 0 {
return errors.NotFound("go.micro.client", "Service not found")
}

n := rand.Int() % len(service.Nodes())
node := service.Nodes()[n]
address := fmt.Sprintf("%s:%d", node.Address(), node.Port())
return r.call(address, "/_rpc", request, response)
}

func (r *RpcClient) NewRequest(service, method string, request interface{}) *RpcRequest {
return r.NewProtoRequest(service, method, request)
}

func (r *RpcClient) NewProtoRequest(service, method string, request interface{}) *RpcRequest {
return newRpcRequest(service, method, request, "application/octet-stream")
}

func (r *RpcClient) NewJsonRequest(service, method string, request interface{}) *RpcRequest {
return newRpcRequest(service, method, request, "application/json")
}

func NewRpcClient() *RpcClient {
return &RpcClient{}
}
45 changes: 45 additions & 0 deletions client/rpc_request.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package client

import (
"net/http"
)

type RpcRequest struct {
service, method, contentType string
request interface{}
headers http.Header
}

func newRpcRequest(service, method string, request interface{}, contentType string) *RpcRequest {
return &RpcRequest{
service: service,
method: method,
request: request,
contentType: contentType,
headers: make(http.Header),
}
}

func (r *RpcRequest) ContentType() string {
return r.contentType
}

func (r *RpcRequest) Headers() Headers {
return r.headers
}

func (r *RpcRequest) Service() string {
return r.service
}

func (r *RpcRequest) Method() string {
return r.method
}

func (r *RpcRequest) Request() interface{} {
return r.request
}

func NewRpcRequest(service, method string, request interface{}, contentType string) *RpcRequest {
return newRpcRequest(service, method, request, contentType)
}
81 changes: 81 additions & 0 deletions errors/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package errors

import (
"encoding/json"
"net/http"
)

type Error struct {
Id string `json:"id"`
Code int32 `json:"code"`
Detail string `json:"detail"`
Status string `json:"status"`
}

func (e *Error) Error() string {
b, _ := json.Marshal(e)
return string(b)
}

func New(id, detail string, code int32) error {
return &Error{
Id: id,
Code: code,
Detail: detail,
Status: http.StatusText(int(code)),
}
}

func Parse(err string) *Error {
var e *Error
errr := json.Unmarshal([]byte(err), &e)
if errr != nil {
e.Detail = err
}
return e
}

func BadRequest(id, detail string) error {
return &Error{
Id: id,
Code: 400,
Detail: detail,
Status: http.StatusText(400),
}
}

func Unauthorized(id, detail string) error {
return &Error{
Id: id,
Code: 401,
Detail: detail,
Status: http.StatusText(401),
}
}

func Forbidden(id, detail string) error {
return &Error{
Id: id,
Code: 403,
Detail: detail,
Status: http.StatusText(403),
}
}

func NotFound(id, detail string) error {
return &Error{
Id: id,
Code: 404,
Detail: detail,
Status: http.StatusText(404),
}
}

func InternalServerError(id, detail string) error {
return &Error{
Id: id,
Code: 500,
Detail: detail,
Status: http.StatusText(500),
}
}
30 changes: 30 additions & 0 deletions examples/service_client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package main

import (
"fmt"

"code.google.com/p/goprotobuf/proto"
"github.com/asim/go-micro/client"
example "github.com/asim/go-micro/template/proto/example"
)

func main() {
// Create new request to service go.micro.service.go-template, method Example.Call
req := client.NewRequest("go.micro.service.template", "Example.Call", &example.Request{
Name: proto.String("John"),
})

// Set arbitrary headers
req.Headers().Set("X-User-Id", "john")
req.Headers().Set("X-From-Id", "script")

rsp := &example.Response{}

// Call service
if err := client.Call(req, rsp); err != nil {
fmt.Println(err)
return
}

fmt.Println(rsp.GetMsg())
}
Loading

0 comments on commit 8e55cde

Please sign in to comment.