Skip to content

Commit

Permalink
Complete extraction of routes and refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
josh-keller committed Feb 7, 2022
1 parent 52aa320 commit 9ca375f
Show file tree
Hide file tree
Showing 7 changed files with 115 additions and 67 deletions.
27 changes: 27 additions & 0 deletions handle_bin_inspect.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package main

import (
"net/http"
)

func (s *server) handleBinInspect() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
binID := r.URL.Path[len("/inspect/"):]

bin, exists := s.db.FindBin(binID)

if !exists {
http.NotFound(w, r)
return
}

s.renderTemplate(w, "inspect", &bin)
return
default:
http.NotFound(w, r)
return
}
}
}
57 changes: 57 additions & 0 deletions handle_bin_inspect_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package main

import (
"bytes"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

"github.com/matryer/is"
)

func TestBinInspect(t *testing.T) {
is := is.New(t)

srv, err := newServer()
srv.db.Connect()
defer srv.db.Disconnect()
is.NoErr(err) // newServer error

hsrv := httptest.NewServer(srv)
defer hsrv.Close()

req, err := http.NewRequest("POST", hsrv.URL+"/new/", nil)
is.NoErr(err) // NewRequest error
client := &http.Client{
Timeout: 1 * time.Minute,
}

resp, err := client.Do(req)
is.NoErr(err) // Client request error
is.Equal(resp.StatusCode, 200) // Making new bin gives 200

inspectURL := hsrv.URL + "/inspect/"
binID := resp.Request.URL.String()[len(inspectURL):]

var reqBody = []byte(`{"request":"Golang test request"}`)
req, err = http.NewRequest("POST", hsrv.URL+"/r/"+binID, bytes.NewBuffer(reqBody))
is.NoErr(err) // New Request error
req.Header.Set("X-Custom-Header", "custom value 2468")
req.Header.Set("Content-type", "application/json")
resp, err = client.Do(req)
is.NoErr(err) // Client request error
is.Equal(resp.StatusCode, 200) // Initial request returns 200

req, err = http.NewRequest("GET", inspectURL+binID, nil)
is.NoErr(err) // New Request error
resp, err = client.Do(req)
is.NoErr(err) // Client request error
is.Equal(resp.StatusCode, 200) // Inspect returns 200
body, err := ioutil.ReadAll(resp.Body)
is.NoErr(err) // body read error
is.True(strings.Contains(string(body), "custom value 2468"))
is.True(strings.Contains(string(body), "Golang test request"))
}
3 changes: 3 additions & 0 deletions handle_bin_new_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ func TestBinNew(t *testing.T) {
is := is.New(t)

srv, err := newServer()
srv.db.Connect()
defer srv.db.Disconnect()

is.NoErr(err) // newServer error

hsrv := httptest.NewServer(srv)
Expand Down
19 changes: 19 additions & 0 deletions handle_rekwest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package main

import (
"fmt"
"net/http"
)

func (s *server) handleRequest() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
binID := r.URL.Path[len("/r/"):]
fmt.Println("Request made: ", binID)

if err := s.db.AddRekwest(binID, r); err == nil {
fmt.Fprintf(w, "Request saved. (ip: %s)", r.RemoteAddr)
} else {
http.NotFound(w, r)
}
}
}
70 changes: 6 additions & 64 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package main
import (
"flag"
"fmt"
"html/template"
"net/http"
"os"
"path/filepath"
"text/template"
)

func main() {
Expand All @@ -30,6 +30,9 @@ func run(args []string) error {
return err
}

srv.db.Connect()
defer srv.db.Disconnect()

fmt.Printf("Rekwest Bin listening on :%d\n", *port)
return http.ListenAndServe(addr, srv)
}
Expand All @@ -52,8 +55,6 @@ func newServer() (*server, error) {
}

func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.db.Connect()
defer s.db.Disconnect()
s.mux.ServeHTTP(w, r)
}

Expand All @@ -63,68 +64,9 @@ func (s *server) handleIndex() http.HandlerFunc {
}
}

/*
func main() {
db_controller.Connect()
defer db_controller.Disconnect()
http.HandleFunc("/r/", binHandler)
http.HandleFunc("/", rootHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "")
}
func fixIPAddress(r *http.Request) {
var ipAddress string
var ipSources = []string{
r.Header.Get("True-Client-IP"),
r.Header.Get("True-Real-IP"),
r.Header.Get("X-Forwarded-For"),
r.Header.Get("X-Originating-IP"),
}
for _, ip := range ipSources {
if ip != "" {
ipAddress = ip
break
}
}
if ipAddress != "" {
r.RemoteAddr = ipAddress
}
}
func binHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
bin, _ := db_controller.NewBin()
http.Redirect(w, r, "/r/"+bin.BinId+"?inspect", 302)
return
}
binID := r.URL.Path[len("/r/"):]
binAddress := fmt.Sprintf("http://%s/r/%s", r.Host, binID)
if r.URL.RawQuery == "inspect" {
bin, exists := db_controller.FindBin(binID)
if !exists {
http.NotFound(w, r)
return
}
renderTemplate(w, "inspect", &bin)
} else {
}
func renderTemplate(writer http.ResponseWriter, tmpl string, bin *db_controller.Bin) {
err := templates.ExecuteTemplate(writer, tmpl+".html", bin)
func (s *server) renderTemplate(writer http.ResponseWriter, tmpl string, bin *Bin) {
err := s.tmpl.ExecuteTemplate(writer, tmpl+".html", bin)
if err != nil {
http.Error(writer, err.Error(), http.StatusInternalServerError)
}
}
*/
2 changes: 1 addition & 1 deletion public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</head>
<body>
<h1>Welcome to Rekwest Bin</h1>
<form method='POST' action='/r/'>
<form method='POST' action='/new/'>
<button type='submit'>Create a bin</button>
</form>
</body>
Expand Down
4 changes: 2 additions & 2 deletions routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ package main
func (s *server) routes() {
s.mux.HandleFunc("/", s.handleIndex())
s.mux.HandleFunc("/new/", s.handleBinNew())
// s.mux.HandleFunc("/r/", s.fixIPAddress(s.handleRequest()))
// s.mux.HandleFunc("/inspect/", s.handleInspect())
s.mux.HandleFunc("/r/", s.fixIPAddress(s.handleRequest()))
s.mux.HandleFunc("/inspect/", s.handleBinInspect())
}

0 comments on commit 9ca375f

Please sign in to comment.