Skip to content

Instantly share code, notes, and snippets.

@jan4984
Created February 17, 2020 11:00
Show Gist options
  • Save jan4984/92d127aa2966002e9b42275546132038 to your computer and use it in GitHub Desktop.
Save jan4984/92d127aa2966002e9b42275546132038 to your computer and use it in GitHub Desktop.
simple txt copy via web
package main
import (
"fmt"
"html/template"
"io/ioutil"
"net/http"
)
var txt = ""
const html = `<div><textarea style="width:100%" id="t">{{.Text}}</textarea></div>
<div><button id="b">update</button></div>
<script>
const t = document.querySelector('#t');
const b = document.querySelector('#b');
b.addEventListener('click', ()=>{
fetch('/msg', {
method: 'post',
body: t.value});
});
</script>
`
func main(){
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "text/html")
t, err := template.New("webpage").Parse(html)
if(err != nil){
fmt.Println(w, err)
return;
}
data := struct{
Text string
}{
Text: txt,
}
err = t.Execute(w, data)
if(err != nil){
fmt.Println(w, err)
return;
}
})
http.HandleFunc("/msg", func(w http.ResponseWriter, r *http.Request) {
if(r.Method == "POST"){
defer r.Body.Close();
b, _ := ioutil.ReadAll(r.Body)
txt = string(b)
return
}
fmt.Fprintln(w, txt)
})
s := &http.Server{
Addr: ":1999",
}
s.ListenAndServe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment