Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
net/http workshop
package main
import (
"fmt"
"io"
"log"
"net/http"
)
func Handler(w http.ResponseWriter, req *http.Request) {
str := fmt.Sprintln(req)
io.WriteString(w, str)
}
func main() {
http.HandleFunc("/", Handler)
err := http.ListenAndServe(":8000", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
package main
import (
"fmt"
"io"
"log"
"net"
"net/http"
)
func Handler(w http.ResponseWriter, req *http.Request) {
str := fmt.Sprintln(req)
io.WriteString(w, str)
}
func main() {
http.HandleFunc("/", Handler)
listener, err := net.Listen("tcp", ":8001")
err = http.Serve(listener, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
package main
import (
"fmt"
"io"
"log"
"net/http"
)
type MyHandler int64
func (h MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
h++
io.WriteString(w, fmt.Sprintf("counter = %d", h))
}
func main() {
handler := MyHandler(0)
err := http.ListenAndServe(":8002", handler)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
package main
import (
"fmt"
"io"
"log"
"net/http"
)
type MyHandler int64
func (h *MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
//log.Println(req.URL.Path)
*h++
io.WriteString(w, fmt.Sprintf("counter = %d", *h))
}
func main() {
handler := MyHandler(0)
err := http.ListenAndServe(":8002", &handler)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
package main
import (
"fmt"
"io"
"log"
"net/http"
)
var counter int64
type MyIncrementer struct {
}
func (c *MyIncrementer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
//log.Println(req.URL.Path)
counter++
io.WriteString(w, fmt.Sprintf("counter = %d", counter))
}
type MyDecrementer struct {
}
func (d *MyDecrementer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
//log.Println(req.URL.Path)
counter--
io.WriteString(w, fmt.Sprintf("counter = %d", counter))
}
type MyThrough struct {
}
func (d *MyThrough) ServeHTTP(w http.ResponseWriter, req *http.Request) {
//log.Println(req.URL.Path)
// do nothing
io.WriteString(w, fmt.Sprintf("counter = %d", counter))
}
func main() {
incr := &MyIncrementer{}
decr := &MyDecrementer{}
through := &MyThrough{}
mux := http.NewServeMux()
mux.Handle("/", decr) // 人生は減点法です
mux.Handle("/incr", incr)
mux.Handle("/decr", decr)
//mux.Handle("/favicon.ico", through)
err := http.ListenAndServe(":8003", mux)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment