Skip to content
Myr

Add 'GET /' endpoint for getting the program state (experimental)

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

Related #3372

authored by Junegunn Choi · committed by Junegunn Choi · parent c5e4b83 · Browse files · 5 files+121 added−16 removed
This commit

State

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

Diff stats

5 files+121 added−16 removed

  • tests:+13 added−0 removed
  • other:+108 added−16 removed

5 files+121 added−16 removed

modified:man/man1/fzf.1+3 added
793 unmodified lines
794e.g.795 \fB# Start HTTP server on port 6266796 fzf --listen 6266797798 # Get program state in JSON format (experimental)799 curl localhost:6266800801 # Send action to the server802 curl -XPOST localhost:6266 -d 'reload(seq 100)+change-prompt(hundred> )'803804 # Start HTTP server on port 6266 and send an authenticated action
526 unmodified lines
modified:src/server.go+23 added-11 removed
21 unmodified lines
22 maxContentLength = 1024 * 102423)2425type httpServer struct {26 apiKey []byte27 channel chan []*action26 apiKey []byte27 actionChannel chan []*action28 responseChannel chan string29}3030func startHttpServer(port int, channel chan []*action) (error, int) {31func startHttpServer(port int, actionChannel chan []*action, responseChannel chan string) (error, int) {32 if port < 0 {33 return nil, port34 }35
14 unmodified lines
50 }51 }5253 server := httpServer{53 apiKey: []byte(os.Getenv("FZF_API_KEY")),54 channel: channel,54 apiKey: []byte(os.Getenv("FZF_API_KEY")),55 actionChannel: actionChannel,56 responseChannel: responseChannel,57 }5859 go func() {60 for {
23 unmodified lines
84func (server *httpServer) handleHttpRequest(conn net.Conn) string {85 contentLength := 086 apiKey := ""87 body := ""86 unauthorized := func(message string) string {88 answer := func(code string, message string) string {89 message += "\n"88 return httpUnauthorized + fmt.Sprintf("Content-Length: %d%s", len(message), crlf+crlf+message)90 return code + fmt.Sprintf("Content-Length: %d%s", len(message), crlf+crlf+message)91 }92 unauthorized := func(message string) string {93 return answer(httpUnauthorized, message)94 }95 bad := func(message string) string {91 message += "\n"92 return httpBadRequest + fmt.Sprintf("Content-Length: %d%s", len(message), crlf+crlf+message)96 return answer(httpBadRequest, message)97 }98 good := func(message string) string {99 return answer(httpOk+"Content-Type: application/json"+crlf, message)100 }101 conn.SetReadDeadline(time.Now().Add(httpReadTimeout))102 scanner := bufio.NewScanner(conn)103 scanner.Split(func(data []byte, atEOF bool) (int, []byte, error) {104 found := bytes.Index(data, []byte(crlf))
11 unmodified lines
116 for scanner.Scan() {117 text := scanner.Text()118 switch section {119 case 0:120 // TODO: Parameter support e.g. "GET /?limit=100 HTTP"121 if strings.HasPrefix(text, "GET / HTTP") {122 server.actionChannel <- []*action{{t: actResponse}}123 response := <-server.responseChannel124 return good(response)113 if !strings.HasPrefix(text, "POST / HTTP") {125 } else if !strings.HasPrefix(text, "POST / HTTP") {126 return bad("invalid request method")127 }128 section++129 case 1:
41 unmodified lines
171 if len(actions) == 0 {172 return bad("no action specified")173 }174163 server.channel <- actions175 server.actionChannel <- actions176 return httpOk177}
modified:src/terminal.go+74 added-5 removed
1package fzf23import (4 "bufio"5 "encoding/json"6 "fmt"7 "io"8 "math"9 "os"
134 unmodified lines
144var emptyLine = itemLine{}145146type labelPrinter func(tui.Window, int)147148type StatusItem struct {149 Index int `json:"index"`150 Text string `json:"text"`151}152153type Status struct {154 Reading bool `json:"reading"`155 Query string `json:"query"`156 Position int `json:"position"`157 Sort bool `json:"sort"`158 TotalCount int `json:"totalCount"`159 MatchCount int `json:"matchCount"`160 Current *StatusItem `json:"current"`161 Matches []StatusItem `json:"matches"`162 Selected []StatusItem `json:"selected"`163}164165// Terminal represents terminal input/output166type Terminal struct {167 initDelay time.Duration168 infoStyle infoStyle
93 unmodified lines
262 suppress bool263 sigstop bool264 startChan chan fitpad265 killChan chan int248 serverChan chan []*action266 serverInputChan chan []*action267 serverOutputChan chan string268 eventChan chan tui.Event269 slab *util.Slab270 theme *tui.ColorTheme271 tui tui.Renderer
144 unmodified lines
416 actDeselect417 actUnbind418 actRebind419 actBecome420 actResponse421)422423type placeholderFlags struct {424 plus bool
251 unmodified lines
676 slab: util.MakeSlab(slab16Size, slab32Size),677 theme: opts.Theme,678 startChan: make(chan fitpad, 1),679 killChan: make(chan int),660 serverChan: make(chan []*action, 10),680 serverInputChan: make(chan []*action, 10),681 serverOutputChan: make(chan string),682 eventChan: make(chan tui.Event, 1),683 tui: renderer,684 initFunc: func() { renderer.Init() },685 executing: util.NewAtomicBool(false)}
37 unmodified lines
723724 _, t.hasLoadActions = t.keymap[tui.Load.AsEvent()]725726 if t.listenPort != nil {706 err, port := startHttpServer(*t.listenPort, t.serverChan)727 err, port := startHttpServer(*t.listenPort, t.serverInputChan, t.serverOutputChan)728 if err != nil {729 errorExit(err.Error())730 }731 t.listenPort = &port
2101 unmodified lines
2833 t.track = trackDisabled2834 t.printInfo()2835 }2836 if onFocus, prs := t.keymap[tui.Focus.AsEvent()]; prs && focusChanged {2816 t.serverChan <- onFocus2837 t.serverInputChan <- onFocus2838 }2839 if focusChanged || version != t.version {2840 version = t.version2841 focusedIndex = currentIndex
103 unmodified lines
2945 }2946 select {2947 case event = <-t.eventChan:2948 needBarrier = !event.Is(tui.Load, tui.One, tui.Zero)2928 case actions = <-t.serverChan:2949 case actions = <-t.serverInputChan:2950 event = tui.Invalid.AsEvent()2951 needBarrier = false2952 }2953 }
66 unmodified lines
3020 }3021 doAction = func(a *action) bool {3022 switch a.t {3023 case actIgnore:3024 case actResponse:3025 t.serverOutputChan <- t.dumpStatus()3026 case actBecome:3027 valid, list := t.buildPlusList(a.a, false)3028 if valid {3029 command := t.replacePlaceholder(a.a, false, string(t.input), list)
760 unmodified lines
3790 max++3791 }3792 return util.Max(max, 0)3793}37943795func (t *Terminal) dumpItem(i *Item) StatusItem {3796 if i == nil {3797 return StatusItem{}3798 }3799 return StatusItem{3800 Index: int(i.Index()),3801 Text: i.AsString(t.ansi),3802 }3803}38043805const dumpItemLimit = 100 // TODO: Make configurable via GET parameter38063807func (t *Terminal) dumpStatus() string {3808 selectedItems := t.sortSelected()3809 selected := make([]StatusItem, util.Min(dumpItemLimit, len(selectedItems)))3810 for i, selectedItem := range selectedItems[:len(selected)] {3811 selected[i] = t.dumpItem(selectedItem.item)3812 }38133814 matches := make([]StatusItem, util.Min(dumpItemLimit, t.merger.Length()))3815 for i := range matches {3816 matches[i] = t.dumpItem(t.merger.Get(i).item)3817 }38183819 var current *StatusItem3820 currentItem := t.currentItem()3821 if currentItem != nil {3822 item := t.dumpItem(currentItem)3823 current = &item3824 }38253826 dump := Status{3827 Reading: t.reading,3828 Query: string(t.input),3829 Position: t.cy,3830 Sort: t.sort,3831 TotalCount: t.count,3832 MatchCount: t.merger.Length(),3833 Current: current,3834 Matches: matches,3835 Selected: selected,3836 }3837 bytes, _ := json.Marshal(&dump) // TODO: Errors?3838 return string(bytes)3839}
modified:test/test_go.rb+13 added
6 unmodified lines
7require 'shellwords'8require 'erb'9require 'tempfile'10require 'net/http'11require 'json'1213TEMPLATE = DATA.read14UNSETS = %w[15 FZF_DEFAULT_COMMAND FZF_DEFAULT_OPTS
2760 unmodified lines
2776 "--listen --sync --bind 'start:execute-silent:echo $FZF_PORT > /tmp/fzf-port'" =>2777 -> { URI("http://localhost:#{File.read('/tmp/fzf-port').chomp}") } }.each do |opts, fn|2778 tmux.send_keys "seq 10 | fzf #{opts}", :Enter2779 tmux.until { |lines| assert_equal 10, lines.item_count }2780 state = JSON.parse(Net::HTTP.get(fn.call), symbolize_names: true)2781 assert_equal 10, state[:totalCount]2782 assert_equal 10, state[:matchCount]2783 assert_empty state[:query]2784 assert_equal({ index: 0, text: '1' }, state[:current])27852786 Net::HTTP.post(fn.call, 'change-query(yo)+reload(seq 100)+change-prompt:hundred> ')2787 tmux.until { |lines| assert_equal 100, lines.item_count }2788 tmux.until { |lines| assert_equal 'hundred> yo', lines[-1] }2789 state = JSON.parse(Net::HTTP.get(fn.call), symbolize_names: true)2790 assert_equal 100, state[:totalCount]2791 assert_equal 0, state[:matchCount]2792 assert_equal 'yo', state[:query]2793 assert_nil state[:current]27942795 teardown2796 setup2797 end2798 end
709 unmodified lines
modified:CHANGELOG.md+8 added
12 unmodified lines
1314 # Client15 curl localhost:6266 -H "x-api-key: $FZF_API_KEY" -d 'change-query(yo)'16 ```17- `--listen` server can report program state in JSON format (`GET /`)18 ```sh19 # fzf server started in "headless" mode20 fzf --listen 6266 2> /dev/null2122 # Get program state23 curl localhost:6266 | jq .24 ```25- Added `toggle-header` action26- Bug fixes27280.42.0
1664 unmodified lines