Skip to content

Instantly share code, notes, and snippets.

@shortdiv
Created April 15, 2020 15:54
Show Gist options
  • Save shortdiv/cbb55f05f835d1cc4b568cd87d99ba28 to your computer and use it in GitHub Desktop.
Save shortdiv/cbb55f05f835d1cc4b568cd87d99ba28 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io"
"log"
"net/http"
"strings"
)
type Response struct {
http.ResponseWriter
}
func (r *Response) Text(code int, body string) {
r.Header().Set("Content-Type", "text/plain")
r.WriteHeader(code)
io.WriteString(r, fmt.Sprintf("%s\n", body))
}
func main() {
handler := http.NewServeMux()
handler.HandleFunc("/hello/", func(w http.ResponseWriter, r *http.Request) {
name := strings.Replace(r.URL.Path, "/hello/", "", 1)
resp := Response{w}
resp.Text(http.StatusOK, fmt.Sprintf("hello %s", name))
})
handler.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "hello stranger")
})
log.Fatal(http.ListenAndServe(":8080", handler))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment