Skip to content

Instantly share code, notes, and snippets.

@peterhellberg
Last active May 20, 2024 09:39
Show Gist options
  • Save peterhellberg/3a32f4869ff4e8e4b2859a8ce834e429 to your computer and use it in GitHub Desktop.
Save peterhellberg/3a32f4869ff4e8e4b2859a8ce834e429 to your computer and use it in GitHub Desktop.
Edit file in Vim over HTTP GET and PUT
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{})
}
@peterhellberg
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment