Skip to content

Instantly share code, notes, and snippets.

@wingyplus
Created June 23, 2016 05:17
Show Gist options
  • Save wingyplus/0c63356bf9fb2c63a8111715ed2c116a to your computer and use it in GitHub Desktop.
Save wingyplus/0c63356bf9fb2c63a8111715ed2c116a to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
type ErrorResponse struct {
Text string `json:"text"`
ErrorCode string `json:"error_code"`
}
func logAccess(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Println(time.Now().Format(time.RFC3339), r.Method, r.URL.Path)
handler(w, r)
}
}
func getMethod(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
handler(w, r)
}
}
}
func postMethod(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
handler(w, r)
}
}
}
func index(w http.ResponseWriter, r *http.Request) {
m := ErrorResponse{Text: "Hello, AIS", ErrorCode: "1000"}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(m)
}
func web(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `<!doctype html>
<html><body><h1>Hello, AIS</h1></body></html>`)
}
type FileContactList struct {
f *os.File
}
func (cl *FileContactList) Save(tel string) {
fmt.Fprintf(cl.f, `{"tel":"%s"}`+"\n", tel)
}
type ContactList interface {
Save(tel string)
}
type ContactHandler struct {
contactList ContactList
}
func (ch *ContactHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ch.contactList.Save("11111111")
w.Write([]byte("Hello, AIS"))
}
func main() {
var file *os.File
file, _ = os.OpenFile("hello.txt", os.O_CREATE|os.O_WRONLY, 0755)
http.HandleFunc("/", getMethod(logAccess(index)))
http.HandleFunc("/index.html", getMethod(logAccess(web)))
http.Handle("/contact", &ContactHandler{
contactList: &FileContactList{f: file},
})
http.ListenAndServe(":9000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment