Skip to content

Commit

Permalink
Merge pull request #99 from azimjohn/new-jprq
Browse files Browse the repository at this point in the history
[release] jprq 2.0
  • Loading branch information
azimjohn committed Feb 27, 2023
2 parents e1ef327 + a592150 commit bc401f2
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 80 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go.sum
package.json

# binaries
bin/
cli/jprq
server/jprq-server
website/jprq-website
14 changes: 14 additions & 0 deletions build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
GOOS=darwin GOARCH=amd64 go build -o bin/jprq-darwin-amd64 cli/*.go
GOOS=darwin GOARCH=arm64 go build -o bin/jprq-darwin-arm64 cli/*.go
GOOS=linux GOARCH=386 go build -o bin/jprq-linux-386 cli/*.go
GOOS=linux GOARCH=amd64 go build -o bin/jprq-linux-amd64 cli/*.go
GOOS=linux GOARCH=arm go build -o bin/jprq-linux-arm cli/*.go
GOOS=linux GOARCH=arm64 go build -o bin/jprq-linux-arm64 cli/*.go
GOOS=linux GOARCH=ppc64 go build -o bin/jprq-linux-ppc64 cli/*.go
GOOS=linux GOARCH=ppc64le go build -o bin/jprq-linux-ppc64le cli/*.go
GOOS=linux GOARCH=mips go build -o bin/jprq-linux-mips cli/*.go
GOOS=linux GOARCH=mipsle go build -o bin/jprq-linux-mipsle cli/*.go
GOOS=linux GOARCH=mips64 go build -o bin/jprq-linux-mips64 cli/*.go
GOOS=linux GOARCH=mips64le go build -o bin/jprq-linux-mips64le cli/*.go
GOOS=windows GOARCH=386 go build -o bin/jprq-windows-386.exe cli/*.go
GOOS=windows GOARCH=amd64 go build -o bin/jprq-windows-amd64.exe cli/*.go
61 changes: 23 additions & 38 deletions cli/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,76 +2,61 @@ package http

import (
"bufio"
"io"
"net/http"
"strconv"
)

type Request struct {
Id string `json:"id"`
Method string `json:"method"`
URL string `json:"url"`
Body string `json:"body"`
Headers map[string]string `json:"headers"`
Id string `json:"id"`
Method string `json:"method"`
URL string `json:"url"`
Body string `json:"body"`
Headers map[string][]string `json:"headers"`
}

type Response struct {
RequestId string `json:"request_id"`
Status int `json:"status"`
Headers map[string]string `json:"headers"`
Body string `json:"body"`
RequestId string `json:"request_id"`
Status int `json:"status"`
Headers map[string][]string `json:"headers"`
Body string `json:"body"`
}

func ParseRequests(conn io.Reader, connID string) <-chan Request {
i := 0
func ParseRequests(r *bufio.Reader, connID string) <-chan Request {
ch := make(chan Request)
reader := bufio.NewReader(conn)
go func() {
for {
req, err := http.ReadRequest(reader)
for i := 0; ; i++ {
req, err := http.ReadRequest(r)
if err != nil {
close(ch)
break
}
r := Request{
Id: connID + strconv.Itoa(i),
Method: req.Method,
URL: req.URL.String(),
Body: "<todo>",
ch <- Request{
Id: connID + strconv.Itoa(i),
Method: req.Method,
URL: req.URL.String(),
Body: "<todo>",
Headers: req.Header,
}
r.Headers = make(map[string]string)
for key, value := range req.Header {
r.Headers[key] = value[0]
}
ch <- r
i++
}
}()
return ch
}

func ParseResponses(conn io.Reader, connID string) <-chan Response {
i := 0
func ParseResponses(r *bufio.Reader, connID string) <-chan Response {
ch := make(chan Response)
reader := bufio.NewReader(conn)
go func() {
for {
resp, err := http.ReadResponse(reader, nil)
for i := 0; ; i++ {
resp, err := http.ReadResponse(r, nil)
if err != nil {
close(ch)
break
}
r := Response{
ch <- Response{
RequestId: connID + strconv.Itoa(i),
Status: resp.StatusCode,
Body: "<todo>",
Headers: resp.Header,
}
r.Headers = make(map[string]string)
for key, value := range resp.Header {
r.Headers[key] = value[0]
}
ch <- r
i++
}
}()
return ch
Expand Down
11 changes: 0 additions & 11 deletions cli/jprqc.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package main
import (
"encoding/binary"
"fmt"
"github.com/azimjohn/jprq/cli/web"
"github.com/azimjohn/jprq/server/events"
"github.com/azimjohn/jprq/server/tunnel"
"log"
Expand All @@ -18,7 +17,6 @@ type jprqClient struct {
localServer string
remoteServer string
publicServer string
webInterface web.WebServer
}

func (j *jprqClient) Start(port int) {
Expand Down Expand Up @@ -53,7 +51,6 @@ func (j *jprqClient) Start(port int) {
j.publicServer = fmt.Sprintf("%s:%d", tunnel.Data.Hostname, tunnel.Data.PublicServer)

if j.protocol == "http" {
go j.runWebInterface(4444)
j.publicServer = fmt.Sprintf("https://%s", tunnel.Data.Hostname)
}

Expand Down Expand Up @@ -92,11 +89,3 @@ func (j *jprqClient) handleEvent(event events.ConnectionReceived) {
go tunnel.Bind(localCon, remoteCon)
tunnel.Bind(remoteCon, localCon)
}

func (j *jprqClient) runWebInterface(port uint16) {
j.webInterface = web.NewWebServer()
fmt.Printf("Web Interface: \t http://127.0.0.1:%d (for debugging)\n", port)
if err := j.webInterface.Run(port); err != nil {
fmt.Printf("Web Interface: \t failed to run on port %d\n", port)
}
}
2 changes: 1 addition & 1 deletion cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func main() {
log.Fatalf("error: cannot reach server on port: %d\n", port)
}

fmt.Printf("jprq: \t%s\n\n", version)
fmt.Printf("jprq %s \t press Ctrl+C to quit\n\n", version)
defer log.Println("jprq tunnel closed")

client := jprqClient{
Expand Down
46 changes: 17 additions & 29 deletions cli/web/static/script.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const requestsEl = document.getElementById("requests");
const infoSections = document.getElementsByClassName("card-info");
let requests = [];
var active_request_id = -1
let active_request_id = -1

for (let infoSection of infoSections) {
let title = infoSection.getElementsByClassName("header-title")[0];

Expand All @@ -28,7 +29,7 @@ function createElementFromHTML(htmlString) {
}

const getMethodColor = (method) => {
colors = {
const colors = {
GET: "sky-500",
POST: "green-500",
PUT: "orange-500",
Expand All @@ -43,7 +44,7 @@ const getMethodColor = (method) => {

const getStatusColor = (status) => {
let first_digit = Math.floor(status / 100);
colors = {
const colors = {
1: "gray-500",
2: "green-500",
3: "yellow-500",
Expand All @@ -58,7 +59,7 @@ const addRequest = (request) => {
let methodColor = getMethodColor(request.method);
const requestElHTML = `
<div class="card cursor-pointer request border-l border-t" onclick="selectRequest(${request.id
})" data-is-active="false" data-id=${request.id}>
})" data-is-active="false" data-id=${request.id}>
<div class="method w-20 text-${methodColor}">${request.method}</div>
<div class="path flex-1 text-black/60" title=${request.url}>
${request.url.slice(0, 20)}${request.url.length > 20 ? "..." : ""}
Expand All @@ -78,6 +79,7 @@ const update_request_status = (request_id, status) => {
statusEl.classList.add(`text-${statusColor}`);
statusEl.innerHTML = status;
};

const prettifyJson = (json_str) => {
return JSON.stringify(json_str, null, 2);
};
Expand All @@ -93,8 +95,6 @@ const selectRequest = (request_id) => {
requestEl.dataset.isActive = false;
}
}

// console.log(requestEl);
};

const makeHeaderItem = (key, val) => {
Expand All @@ -105,12 +105,14 @@ const makeHeaderItem = (key, val) => {
</div>
`
}

const updateRequestTitle = (method, url) => {
const requestMethodEl = document.querySelector('#requestMethod')
const requestUrlEl = document.querySelector('#requestUrl')
requestMethodEl.innerText = method
requestUrlEl.innerText = url
}

const updateRequestHeaders = (requestHeaders) => {
let requestHeadersEl = document.getElementById("info")
.querySelector('[data-title="requestHeaders"]')
Expand All @@ -121,6 +123,7 @@ const updateRequestHeaders = (requestHeaders) => {
})
requestHeadersEl.replaceChildren(createElementFromHTML(requestHeadersHtml))
}

const updateResponseHeaders = (responseHeaders) => {
let responseHeadersEl = document.getElementById("info")
.querySelector('[data-title="responseHeaders"]')
Expand All @@ -134,6 +137,7 @@ const updateResponseHeaders = (responseHeaders) => {
})
responseHeadersEl.replaceChildren(createElementFromHTML(responseHeadersHtml))
}

const updateResponseBody = (responseBody) => {
console.log(responseBody);
let responseBodyEl = document.getElementById("info")
Expand All @@ -145,6 +149,7 @@ const updateResponseBody = (responseBody) => {
responseBodyEl.innerHTML = `
<pre><code class="language-json text-normal">${prettifyJson(responseBody)}</code></pre>`;
}

const updateRequestBody = (requestBody) => {
console.log(requestBody);
let requestBodyEl = document.getElementById("info")
Expand All @@ -156,6 +161,7 @@ const updateRequestBody = (requestBody) => {
requestBodyEl.innerHTML = `
<pre><code class="language-json text-normal">${prettifyJson(requestBody)}</code></pre>`;
}

const highlight_code = () => {
hljs.highlightAll();
}
Expand All @@ -171,38 +177,19 @@ const changeRequestInfo = (request) => {
highlight_code()
};


const handleEvents = async () => {
for (let i = 0; i < 10; i++) {
await new Promise((r) => setTimeout(r, Math.random() * 1000));

handleEvent(
`{"data": {"id": ${i}, "method":"GET","url":"https://google.com","body":"","headers":{"keep-alive":"true"}}}`
);
await new Promise((r) => setTimeout(r, 1500));

setTimeout(() => { }, 3000);
handleEvent(
`{"data": {"request_id": ${i}, "status":200,"headers":{"accept":"Json"},"body":[1,2,3]}}`
);
}
};

const handleEvent = (event_str) => {
let event = JSON.parse(event_str)["data"];
const handleEvent = (e) => {
let event = JSON.parse(e.data);
if ("request_id" in event) {
// Event is response
request = requests.find((request) => request.id === event.request_id);
const request = requests.find((request) => request.id === event.request_id);
if (request) {
request.response = event;
update_request_status(request.id, event.status);
if (request.id === active_request_id) {

updateResponseHeaders(request.response.headers)
updateResponseBody(request.response.body)
highlight_code()
}

}
} else {
try {
Expand All @@ -216,7 +203,8 @@ const handleEvent = (event_str) => {
};

function main() {
handleEvents();
let sse = new EventSource("/events");
sse.onmessage = handleEvent
}

main();
2 changes: 1 addition & 1 deletion server/jprq.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func (j *Jprq) Stop() error {
}

func (j *Jprq) servePublicConn(conn net.Conn) error {
conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
conn.SetReadDeadline(time.Now().Add(time.Second))
host, buffer, err := parseHost(conn)
if err != nil || host == "" {
writeResponse(conn, 400, "Bad Request", "Bad Request")
Expand Down

0 comments on commit bc401f2

Please sign in to comment.