package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"time"
)
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", Index)
router.HandleFunc("/todos", TodoIndex)
//curl -H "Content-Type:application/json" -X GET -i 'http://127.0.0.1:8080/todos/123/zgx'
router.HandleFunc("/todos/{todoId}/{name}", TodoShow)
//curl -H "Content-Type:application/json" -X POST -d '{"name":"zgx","age":30}' -i 'http://127.0.0.1:8080/handlePostJson'
router.HandleFunc("/handlePostJson", handlePostJson)
log.Fatal(http.ListenAndServe(":8080", router))
}
func handlePostJson(w http.ResponseWriter, r *http.Request) {
decoder:=json.NewDecoder(r.Body)
var params map[string]interface{}
decoder.Decode(¶ms)
fmt.Println("POST json req: ",params)
fmt.Fprintln(w,`{"code":0,"msg":"succ"}`)
}
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome!")
}
func TodoIndex(w http.ResponseWriter, r *http.Request) {
//params:= r.URL.Query()
//username:= params.Get("username")
//fmt.Println("request: ",username)
servicetype := r.PostFormValue("servicetype")
fmt.Println("request: ", servicetype)
fmt.Fprintln(w, "Todo Index!")
type Todos []Todo
todos := Todos{
Todo{Name: "Write presentation"},
Todo{Name: "Host meetup"},
}
if err := json.NewEncoder(w).Encode(todos); err != nil {
panic(err)
}
}
type Todo struct {
Name string `json:"name"`
Completed bool `json:"completed"`
Due time.Time `json:"due"`
}
func TodoShow(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
todoId := vars["todoId"]
name := vars["name"]
fmt.Println("request: ", vars)
fmt.Fprintln(w, "response: Id:", todoId, "name:", name)
}