Last active
May 20, 2024 09:39
-
-
Save peterhellberg/3a32f4869ff4e8e4b2859a8ce834e429 to your computer and use it in GitHub Desktop.
Edit file in Vim over HTTP GET and PUT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io" | |
"log" | |
"net/http" | |
"os" | |
"sync" | |
) | |
func main() { | |
l := log.New(os.Stdout, "", 0) | |
d := Data{"/hello": []byte(`Hello, World!`)} | |
s := newServer(l, d) | |
addr := ":9999" | |
l.Printf("Edit by running:\n vim http://127.0.0.1" + addr + "/hello\n") | |
http.ListenAndServe(addr, s) | |
} | |
func newServer(l Logger, d Data) *Server { | |
s := &Server{ | |
ServeMux: &http.ServeMux{}, | |
logger: l, | |
data: d, | |
} | |
s.HandleFunc("GET /", s.get) | |
s.HandleFunc("PUT /", s.put) | |
return s | |
} | |
type Server struct { | |
*http.ServeMux | |
logger Logger | |
mu sync.RWMutex | |
data Data | |
} | |
func (s *Server) get(w http.ResponseWriter, r *http.Request) { | |
s.mu.RLock() | |
defer s.mu.RUnlock() | |
path := r.URL.Path | |
s.logger.Printf("GET %s\n", path) | |
w.Write(s.data[r.URL.Path]) | |
} | |
func (s *Server) put(w http.ResponseWriter, r *http.Request) { | |
s.mu.Lock() | |
defer s.mu.Unlock() | |
path := r.URL.Path | |
s.logger.Printf("PUT %s\n", path) | |
if data, err := io.ReadAll(io.LimitReader(r.Body, 8192)); err == nil { | |
s.data[path] = data | |
} | |
} | |
type Data map[string][]byte | |
type Logger interface { | |
Printf(format string, v ...interface{}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Related to seeing https://mastodon.sdf.org/@conorh/112458241797328014