Skip to content

Commit

Permalink
[UPD][#14] Implemented cobra flags handle, added httphandler generic …
Browse files Browse the repository at this point in the history
…library
  • Loading branch information
Federico Maggi committed Aug 31, 2016
1 parent 093c649 commit 87c13b1
Show file tree
Hide file tree
Showing 10 changed files with 188 additions and 151 deletions.
25 changes: 24 additions & 1 deletion 3n4chatserver/arguments.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,28 @@
package main

const (
kBasePath = "/{version}"
basePath = "/{version}"
)

// Arguments management struct.
type args struct {
// server basic args
verbose bool
// bind address
address string
port int
// mongodb address
dbAddresses string
dbUsername string
dbPassword string
dbAuth string
// https certificates
sslCertificate string
sslPrivateKey string
// rpc authservice
authServiceAddress string
authServicePort int
// workers and queues
workers int
queue int
}
13 changes: 6 additions & 7 deletions 3n4chatserver/authservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,15 @@
// Author: Guido Ronchetti <[email protected]>
// v1.0 16/06/2016
//

package main

// Std golang packages
// Go standard libraries
import (
"fmt"
"net/rpc"
)

// Internal libs
// 3n4 libraries
import (
"github.com/nexocrew/3nigm4/lib/auth"
)
Expand All @@ -26,15 +25,15 @@ type AuthClient interface {
Close() error // closes eventual connections.
}

// AuthRpc implements the RPC default client for
// AuthRPC implements the RPC default client for
// the 3nigm4 auth service.
type AuthRpc struct {
type AuthRPC struct {
client *rpc.Client
}

// NewAuthRpc creates a new instance of the RPC
// NewAuthRPC creates a new instance of the RPC
// client used to interact with the auth service.
func NewAuthRpc(addr string, port int) (*AuthRpc, error) {
func NewAuthRPC(addr string, port int) (*AuthRpc, error) {
address := fmt.Sprintf("%s:%d", addr, port)
rawClient, err := rpc.DialHTTP("tcp", address)
if err != nil {
Expand Down
5 changes: 2 additions & 3 deletions 3n4chatserver/authservice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,16 @@
// concurrency safe and do not implement any performance
// optimisation logic.
//

package main

// Std golang libs
// Go standard libraries
import (
"encoding/hex"
"fmt"
"time"
)

// Internal libs
// 3n4 libraries
import (
"github.com/nexocrew/3nigm4/lib/auth"
ct "github.com/nexocrew/3nigm4/lib/commons"
Expand Down
75 changes: 49 additions & 26 deletions 3n4chatserver/chatservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
// Author: Federico Maggi <[email protected]>
// v1.0 23/08/2016
//

package main

// Go standard libraries
import (
"fmt"
"net/http"
"os"
)

// 3n4 libraries
Expand All @@ -28,42 +28,65 @@ import (
var log *logger.LogFacility

// Cobra parsed arguments
var arguments args
var a args

// RootCmd is the base command used
// by cobra in the chatservice exec.
var RootCmd = &cobra.Command{
Use: "3n4chatserver",
Short: "3nigm4 chat services",
Long: "Command line 3nigm4 chat server.",
RunE: func(cmd *cobra.Command, args []string) error {
printLogo(nil)
// Execution implementation
return fmt.Errorf("undefined command, select a valid one")
},
func init() {
// start up logging facility
log = logger.NewLogFacility("3n4CHAT", true, true)
// init a cobra command
rootCmd := &cobra.Command{
Use: "3n4chatserver",
Short: "a",
Long: "Command line 3nigm4 chat server.",
RunE: func(cmd *cobra.Command, args []string) error {
printLogo(nil)
return fmt.Errorf("undefined command, select a valid one\n")
},
}
// set flags
rootCmd.PersistentFlags().BoolVarP(&a.verbose, "verbose", "v", false, "enable verbose mode")
// database references
rootCmd.PersistentFlags().StringVarP(&a.dbAddresses, "dbaddrs", "d", "127.0.0.1:27017", "the database cluster addresses")
rootCmd.PersistentFlags().StringVarP(&a.dbUsername, "dbuser", "u", "", "the database user name")
rootCmd.PersistentFlags().StringVarP(&a.dbPassword, "dbpwd", "w", "", "the database password")
rootCmd.PersistentFlags().StringVarP(&a.dbAuth, "dbauth", "", "admin", "the database auth db")
// service coordinates
rootCmd.PersistentFlags().StringVarP(&a.address, "address", "a", "0.0.0.0", "the http/https listening address")
rootCmd.PersistentFlags().IntVarP(&a.port, "port", "p", 7443, "the http/https listening port")
// SSL/TLS
rootCmd.PersistentFlags().StringVarP(&a.sslCertificate, "certificate", "s", "", "the SSL/TLS certificate PEM file path")
rootCmd.PersistentFlags().StringVarP(&a.sslPrivateKey, "privatekey", "S", "", "the SSL/TLS private key PEM file path")
// auth RPC service
rootCmd.PersistentFlags().StringVarP(&a.authServiceAddress, "authaddr", "A", "", "the authorisation RPC service address")
rootCmd.PersistentFlags().IntVarP(&a.authServicePort, "authport", "P", 7931, "the authorisation RPC service port")

// parse flags
rootCmd.ParseFlags(os.Args)
}

func main() {
// start up logging facility
log = logger.NewLogFacility("3nigm4_CS", true, true)
serviceAddress := fmt.Sprintf("%s:%d", "localhost", arguments.port) // arguments.address

serviceAddress := fmt.Sprintf("%s:%d", a.address, a.port)
info := make(map[string]string)
info["bind"] = serviceAddress

// print logo
printLogo(info)

if arguments.sslcrt != "" && arguments.sslpvk != "" {
log.MessageLog("Starting listening with TLS on address %s.\n", serviceAddress)
// set up SSL/TLS
fmt.Println("listening")
err := http.ListenAndServeTLS(serviceAddress, arguments.sslcrt, arguments.sslpvk, nil)
fmt.Println("listen returned", err.Error())
if err != nil {
if a.verbose {
log.MessageLog("Certificate: `%s` | Private key: `%s`\n", a.sslCertificate, a.sslPrivateKey)
}

// check for SSL/TLS certificates
if a.sslCertificate == "" || a.sslPrivateKey == "" {
log.ErrorLog("Invalid SSL/TLS certificates paths\n")
os.Exit(1)
}

// fmt.Errorf("https unable to listen and serve on address: %s cause error: %s", serviceAddress, err.Error())
}
// set up SSL/TLS
log.MessageLog("Starting SSL/TLS services on address %s.\n", serviceAddress)
err := http.ListenAndServeTLS(serviceAddress, a.sslCertificate, a.sslPrivateKey, router())
if err != nil {
log.ErrorLog("Unable to listen and serve on address %s. cause: [%s].\n", serviceAddress, err.Error())
}
}

Expand Down
6 changes: 5 additions & 1 deletion 3n4chatserver/resource/res_stat.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@ import (
"net/http"
)

import (
h "github.com/nexocrew/3nigm4/lib/httphandler"
)

type Ping struct{}
type Pong struct {
Status string `json:"status"`
Error string `json:"err"`
}

func (p *Ping) Get(r *http.Request) (int, Resource) {
func (p *Ping) Get(r *http.Request) (int, h.Resource) {
return http.StatusOK, Pong{"ok", ""}
}
67 changes: 10 additions & 57 deletions 3n4chatserver/resource/resource.go
Original file line number Diff line number Diff line change
@@ -1,87 +1,40 @@
package resource

import (
"net/http"
h "github.com/nexocrew/3nigm4/lib/httphandler"
)

const kMuxChatName = "chat_name"

// Resource represents a generic REST resource.
type Resource interface{}

// GetSupported
type GetSupported interface {
Get(*http.Request) (int, Resource)
}

// PostSupported
type PostSupported interface {
Post(*http.Request) (int, Resource)
}

// PutSupported
type PutSupported interface {
Put(*http.Request) (int, Resource)
}

// DeleteSupported
type DeleteSupported interface {
Delete(*http.Request) (int, Resource)
}

// HeadSupported
type HeadSupported interface {
Head(*http.Request) (int, Resource)
}

// PatchSupported
type PatchSupported interface {
Patch(*http.Request) (int, Resource)
}

// ResourcePath defines a route pattern for a resource.
type ResourcePath struct {
resource Resource
pattern string
}

func (r *ResourcePath) GetResource() Resource {
return r.resource
}

func (r *ResourcePath) GetPattern() string {
return r.pattern
}

// GetResources
// returns the route pattterns for all resources
func GetResources() []ResourcePath {
return []ResourcePath{
ResourcePath{
func GetResources() []h.ResourcePath {
return []h.ResourcePath{
h.ResourcePath{
new(Ping),
"/ping",
},
ResourcePath{
h.ResourcePath{
new(ChatCollection),
"/chats",
},
ResourcePath{
h.ResourcePath{
new(ChatResource),
"/chat/{" + kMuxChatName + "}",
},
ResourcePath{
h.ResourcePath{
new(MessagesCollection),
"/chat/{" + kMuxChatName + "}/messages",
},
ResourcePath{
h.ResourcePath{
new(MessagesCollection),
"/chat/{" + kMuxChatName + "}/files",
},
ResourcePath{
h.ResourcePath{
new(MessageResource),
"/chat/{" + kMuxChatName + "}/message",
},
ResourcePath{
h.ResourcePath{
new(MessageResource),
"/chat/{" + kMuxChatName + "}/file",
},
Expand Down
22 changes: 15 additions & 7 deletions 3n4chatserver/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,20 @@
// Author: Federico Maggi <[email protected]>
// v1.0 23/08/2016
//

package main

// Golang std libs
// Go standard libraries
import (
"net/http"
)

// 3n4 libraries
import (
res "github.com/nexocrew/3nigm4/3n4chatserver/resource"
h "github.com/nexocrew/3nigm4/lib/httphandler"
)

// Third party dependencies
// Third party libraries
import (
"github.com/gorilla/mux"
)
Expand All @@ -25,20 +25,28 @@ func router() *mux.Router {
// create router
r := mux.NewRouter()
// define auth routes
r.HandleFunc(kBasePath+"/authsession", login).Methods("POST")
r.HandleFunc(kBasePath+"/authsession", logout).Methods("DELETE")
r.HandleFunc(basePath+"/authsession", login).Methods("POST")
r.HandleFunc(basePath+"/authsession", logout).Methods("DELETE")

// utility routes
// r.HandleFunc(kBasePath+"/ping", ping).Methods("GET")
// r.HandleFunc(basePath+"/ping", ping).Methods("GET")
// r.HandleFunc("/{"+kMuxVersion+"}/backdoor", backdoor).Methods("GET")

// REST resources
paths := res.GetResources()
for _, path := range paths {
r.HandleFunc(kBasePath+path.GetPattern(), newHandler(path.GetResource()))
r.HandleFunc(basePath+path.Pattern, h.Handler(path.Resource))
}
// root routes
http.Handle("/", r)

return r
}

func login(rw http.ResponseWriter, request *http.Request) {

}

func logout(rw http.ResponseWriter, request *http.Request) {

}
14 changes: 0 additions & 14 deletions 3n4chatserver/types.go

This file was deleted.

Loading

0 comments on commit 87c13b1

Please sign in to comment.