Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@ff/server v0.0.1 #18

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions assets/data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"a": 1,
"b": 2,
"c": 3
}
8 changes: 0 additions & 8 deletions cmd/main.go

This file was deleted.

16 changes: 13 additions & 3 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
package main

import "fmt"
import (
"log"
"net/http"

"github.com/rog-golang-buddies/rapidmidiex/www"
)

func main() {
// Feel free to delete this file.
fmt.Println("Hello Gophers")
if err := run(); err != nil {
log.Fatalln(err)
}
}

func run() error {
return http.ListenAndServe(":8081", www.NewService())
Copy link
Contributor

@pmoieni pmoieni Aug 3, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add graceful shutdown and define a stdlib server struct like this to handle timeout and idle situations:

server := http.Server{
   	Addr:         s.Port,
   	Handler:      handler,
   	ErrorLog:     log.Default(),     // set the logger for the server
   	ReadTimeout:  10 * time.Second,  // max time to read request from the client
   	WriteTimeout: 10 * time.Second,  // max time to write response to the client
   	IdleTimeout:  120 * time.Second, // max time for connections using TCP Keep-Alive
   	BaseContext: func(_ net.Listener) context.Context {
   		return serverCtx
   	},
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

graceful shutdown can be added here, may use a builder pattern as timeouts may be configurable from command line.

}
10 changes: 10 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
module github.com/rog-golang-buddies/rapidmidiex

go 1.18

require (
github.com/go-chi/chi/v5 v5.0.7
gotest.tools v2.2.0+incompatible
)

require (
github.com/google/go-cmp v0.5.8 // indirect
github.com/pkg/errors v0.9.1 // indirect
)
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
github.com/go-chi/chi/v5 v5.0.7 h1:rDTPXLDHGATaeHvVlLcR4Qe0zftYethFucbjVQ1PxU8=
github.com/go-chi/chi/v5 v5.0.7/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo=
gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw=
36 changes: 36 additions & 0 deletions www/routes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package www

import "net/http"

// This can be used as a ping-pong test to check if the server is up and running.
// GET /ping
func (s Service) handlePing() http.HandlerFunc {
pmoieni marked this conversation as resolved.
Show resolved Hide resolved
return func(w http.ResponseWriter, r *http.Request) {
s.respond(w, r, "pong", http.StatusOK)
}
}

func (s Service) routes() {
s.m.Handle("/assets/*", s.fileServer("/assets/", "assets"))

s.m.Get("/ping", s.handlePing())

s.m.Get("/ws/jam/{id}", s.handleTransmitMIDI())
s.m.Get("/ws/signal/{id}", s.handleP2PSignal())
}

// Transmitting MIDI and other Jam Session-specific messages between musicians
// GET /ws/jam/{id}
func (s Service) handleTransmitMIDI() http.HandlerFunc {
pmoieni marked this conversation as resolved.
Show resolved Hide resolved
return func(w http.ResponseWriter, r *http.Request) {
s.notImplemented(w, r)
}
}

// Initialize WebRTC connections between peers in a specific Jam Session
// GET /ws/signal/{id}
func (s Service) handleP2PSignal() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s.notImplemented(w, r)
}
}
50 changes: 50 additions & 0 deletions www/routes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package www

import (
"net/http"
"net/http/httptest"
"strings"
"testing"

"gotest.tools/assert" // easy to use testing framework
)

func TestRoutes(t *testing.T) {
type testcase struct {
Name string
PathName string
Method string
ContentType string
Content string
Status int
}

tt := []testcase{
// {Name: "serving assets", PathName: "/assets/data.json", Method: "GET", Status: http.StatusOK}, // httptest can't test this
{Name: "ping pong test", PathName: "/ping", Method: "GET", Status: http.StatusOK},
{Name: "transmitting midi", PathName: "/ws/jam/0", Method: "GET", Status: http.StatusNotImplemented},
{Name: "creating p2p connection", PathName: "/ws/signal/0", Method: "GET", Status: http.StatusNotImplemented},
}

srv := httptest.NewServer(NewService())

for _, tc := range tt {
if tc.ContentType == "" {
tc.ContentType = "application/json"
}
if tc.Status == 0 {
tc.Status = http.StatusOK
}
t.Run(tc.Name, func(t *testing.T) {
req, err := http.NewRequest(tc.Method, srv.URL+tc.PathName, strings.NewReader(tc.Content))
assert.Equal(t, err, nil)

req.Header.Add("Content-Type", tc.ContentType)

res, err := srv.Client().Do(req)
assert.Equal(t, err, nil)

assert.Equal(t, res.StatusCode, tc.Status)
})
}
}
57 changes: 57 additions & 0 deletions www/service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package www

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

"github.com/go-chi/chi/v5"
)

type Service struct {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Service is a general name. use a more specific name like JamService. because not all of the services are gonna have the same struct types and parameters.

m *chi.Mux
}

func NewService() *Service {
s := &Service{
m: chi.NewMux(),
}
s.routes()
return s
}

func (s Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.m.ServeHTTP(w, r)
}

// Send data to the client in json format
func (s Service) respond(rw http.ResponseWriter, r *http.Request, data interface{}, status int) {
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
rw.WriteHeader(status)
if data != nil {
err := json.NewEncoder(rw).Encode(data)
if err != nil {
http.Error(rw, "Could not encode in json", status)
}
}
}

// Decode the request body into the given struct
func (s Service) decode(rw http.ResponseWriter, r *http.Request, data interface{}) (err error) {
return json.NewDecoder(r.Body).Decode(data)
}

// When the request is successful but no data to send
func (s Service) created(rw http.ResponseWriter, r *http.Request, id string) {
rw.Header().Add("Location", "//"+r.Host+r.URL.Path+"/"+id)
s.respond(rw, r, nil, http.StatusCreated)
}

// Endpoint is currently in progress
func (s Service) notImplemented(rw http.ResponseWriter, r *http.Request) {
s.respond(rw, r, nil, http.StatusNotImplemented)
}

// File server helper
func (s Service) fileServer(prefix, dirname string) http.Handler {
return http.StripPrefix(prefix, http.FileServer(http.Dir(dirname)))
}