Skip to content

Commit

Permalink
implement REST interface
Browse files Browse the repository at this point in the history
  • Loading branch information
yashhere committed Feb 13, 2019
1 parent 25a7792 commit 287124f
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 6 deletions.
42 changes: 36 additions & 6 deletions api/library.proto
Original file line number Diff line number Diff line change
@@ -1,14 +1,44 @@
syntax = "proto3";
package library;
import "google/protobuf/timestamp.proto";
import "google/api/annotations.proto";

service LibraryService {
rpc ListAllBooks(Empty) returns (Books);
rpc AddBook(Book) returns (Response);
rpc DeleteBook(QueryFormat) returns (Response);
rpc SearchBook(QueryFormat) returns (Response);
rpc IssueBook(QueryFormat) returns (Response);
rpc ReturnBook(QueryFormat) returns (Response);
rpc ListAllBooks(Empty) returns (Books) {
option (google.api.http) = {
get : "/listBooks"
};
};
rpc AddBook(Book) returns (Response) {
option (google.api.http) = {
post : "/addBook"
body : "*"
};
};
rpc DeleteBook(QueryFormat) returns (Response) {
option (google.api.http) = {
post : "/deleteBook"
body : "*"
};
};
rpc SearchBook(QueryFormat) returns (Response) {
option (google.api.http) = {
post : "/searchBook"
body : "*"
};
};
rpc IssueBook(QueryFormat) returns (Response) {
option (google.api.http) = {
post : "/issueBook"
body : "*"
};
};
rpc ReturnBook(QueryFormat) returns (Response) {
option (google.api.http) = {
post : "/returnBook"
body : "*"
};
};
}

// the library
Expand Down
2 changes: 2 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const (
)

func main() {
clientAddr := fmt.Sprintf("localhost%s", port)
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
Expand All @@ -23,5 +24,6 @@ func main() {
}()

library.InitializeLibrary()
go library.StartHTTPServer(clientAddr)
library.StartLibraryServer(lis)
}
38 changes: 38 additions & 0 deletions pkg/librarylib/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ package server

import (
"context"
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"os"
"time"

"github.com/grpc-ecosystem/grpc-gateway/runtime"

library "personal-learning/go-library/api"

ptypes "github.com/golang/protobuf/ptypes"
Expand All @@ -21,6 +25,10 @@ var (

type server struct{}

type errorBody struct {
Err string `json:"error,omitempty"`
}

/*
InitializeLibrary is used to Initialize the libraryData variable.
We are using a global variable to store our library data. This way
Expand Down Expand Up @@ -279,6 +287,21 @@ func (s *server) ReturnBook(ctx context.Context, query *library.QueryFormat) (*l
return res, nil
}

// StartHTTPServer - Start the HTTP Server
func StartHTTPServer(clientAddr string) {
log.Printf("Starting HTTP Server...")
runtime.HTTPError = CustomHTTPError

addr := ":8181"
opts := []grpc.DialOption{grpc.WithInsecure()}
mux := runtime.NewServeMux()
if err := library.RegisterLibraryServiceHandlerFromEndpoint(context.Background(), mux, clientAddr, opts); err != nil {
log.Fatalf("failed to start HTTP server: %v", err)
}
log.Printf("HTTP Listening on %s\n", addr)
log.Fatal(http.ListenAndServe(addr, mux))
}

// StartLibraryServer - Start the GRPC Server
func StartLibraryServer(lis net.Listener) {
log.Printf("Starting GRPC server...")
Expand All @@ -292,3 +315,18 @@ func StartLibraryServer(lis net.Listener) {
os.Exit(1)
}
}

// CustomHTTPError - Custom HTTP error on errors in StartHTTPServer
func CustomHTTPError(ctx context.Context, _ *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, _ *http.Request, err error) {
const fallback = `{"error": "failed to marshal error message"}`

w.Header().Set("Content-type", marshaler.ContentType())
w.WriteHeader(runtime.HTTPStatusFromCode(grpc.Code(err)))
jErr := json.NewEncoder(w).Encode(errorBody{
Err: grpc.ErrorDesc(err),
})

if jErr != nil {
w.Write([]byte(fallback))
}
}

0 comments on commit 287124f

Please sign in to comment.