Skip to content
Myr

Rewrite HTTP server without net/http

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This cuts down the binary size from 5.7MB to 3.3MB.

authored by Junegunn Choi · committed by Junegunn Choi · parent 1ba7484 · Browse files · 2 files+113 added−36 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+113 added−36 removed

  • other:+113 added−36 removed

2 files+113 added−36 removed

added:src/server.go+112 added
1package fzf23import (4 "bufio"5 "bytes"6 "errors"7 "fmt"8 "net"9 "strconv"10 "strings"11)1213const (14 crlf = "\r\n"15 httpOk = "HTTP/1.1 200 OK" + crlf16 httpBadRequest = "HTTP/1.1 400 Bad Request" + crlf17)1819func startHttpServer(port int, channel chan []*action) {20 if port == 0 {21 return22 }2324 listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port))25 if err != nil {26 return27 }2829 go func() {30 for {31 conn, err := listener.Accept()32 if err != nil {33 if errors.Is(err, net.ErrClosed) {34 break35 } else {36 continue37 }38 }39 conn.Write([]byte(handleHttpRequest(conn, channel)))40 conn.Close()41 }42 listener.Close()43 }()44}4546// Here we are writing a simplistic HTTP server without using net/http47// package to reduce the size of the binary.48//49// * No --listen: 2.8MB50// * --listen with net/http: 5.7MB51// * --listen w/o net/http: 3.3MB52func handleHttpRequest(conn net.Conn, channel chan []*action) string {53 line := 054 headerRead := false55 contentLength := 056 body := ""57 bad := func(message string) string {58 message += "\n"59 return httpBadRequest + fmt.Sprintf("Content-Length: %d%s", len(message), crlf+crlf+message)60 }61 scanner := bufio.NewScanner(conn)62 scanner.Split(func(data []byte, atEOF bool) (int, []byte, error) {63 found := bytes.Index(data, []byte(crlf))64 if found >= 0 {65 token := data[:found+len(crlf)]66 return len(token), token, nil67 }68 if atEOF || len(body)+len(data) >= contentLength {69 return 0, data, bufio.ErrFinalToken70 }71 return 0, nil, nil72 })7374 for scanner.Scan() {75 text := scanner.Text()76 if line == 0 && !strings.HasPrefix(text, "POST / HTTP") {77 return bad("invalid request method")78 }79 if text == crlf {80 headerRead = true81 }82 if !headerRead {83 pair := strings.SplitN(text, ":", 2)84 if len(pair) == 2 && strings.ToLower(pair[0]) == "content-length" {85 length, err := strconv.Atoi(strings.TrimSpace(pair[1]))86 if err != nil {87 return bad("invalid content length")88 }89 contentLength = length90 }91 } else if contentLength <= 0 {92 break93 } else {94 body += text95 }96 line++97 }9899 errorMessage := ""100 actions := parseSingleActionList(strings.TrimSpace(string(body)), func(message string) {101 errorMessage = message102 })103 if len(errorMessage) > 0 {104 return bad(errorMessage)105 }106 if len(actions) == 0 {107 return bad("no action specified")108 }109110 channel <- actions111 return httpOk112}
modified:src/terminal.go+1 added-36 removed
1 unmodified line
23import (4 "bufio"5 "fmt"6 "io"6 "io/ioutil"7 "math"9 "net/http"8 "os"9 "os/signal"10 "regexp"11 "sort"
611 unmodified lines
623624 return &t625}626629func (t *Terminal) startServer() {630 if t.listenPort == 0 {631 return632 }633634 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {635 if r.Method != "POST" {636 w.WriteHeader(http.StatusBadRequest)637 return638 }639 body, err := io.ReadAll(r.Body)640 if err != nil {641 w.WriteHeader(http.StatusBadRequest)642 return643 }644645 response := ""646 actions := parseSingleActionList(string(body), func(message string) {647 response = message648 })649650 if len(response) > 0 {651 w.WriteHeader(http.StatusBadRequest)652 fmt.Fprintln(w, response)653 return654 }655 t.serverChan <- actions656 })657 go func() {658 http.ListenAndServe(fmt.Sprintf(":%d", t.listenPort), nil)659 }()660}661627func borderLines(shape tui.BorderShape) int {628 switch shape {629 case tui.BorderHorizontal, tui.BorderRounded, tui.BorderSharp, tui.BorderBold, tui.BorderDouble:630 return 2
1868 unmodified lines
24992500 looping := true2501 _, startEvent := t.keymap[tui.Start.AsEvent()]25022538 t.startServer()2503 startHttpServer(t.listenPort, t.serverChan)2504 eventChan := make(chan tui.Event)2505 needBarrier := true2506 barrier := make(chan bool)2507 go func() {
686 unmodified lines