- go version go1.12.4 windows/amd64
talk is cheap, show me the code.
package main
import (
"container/list"
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
)
func main() {
http.HandleFunc("/", IndexHandler)
http.HandleFunc("/about", AboutHandler)
http.HandleFunc("/time", TimeHandler)
http.ListenAndServe(":8080", nil)
}
func IndexHandler(writer http.ResponseWriter, request *http.Request) {
println(request.RequestURI)
println(request.FormValue("t"))
list := list.New()
list.PushBack("<a href='/' target='_blank'>index</a><br/>")
list.PushBack("<a href='/about' target='_blank'>about</a><br/>")
list.PushBack("<a href='/time' target='_blank'>time</a><br/>")
for {
e := list.Front()
if e == nil {
break
}
fmt.Fprintf(writer, fmt.Sprint(e.Value))
list.Remove(e)
}
}
func AboutHandler(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintf(writer, "This program be designed by tanpenggood.")
}
func TimeHandler(writer http.ResponseWriter, request *http.Request) {
myMap := NewMap()
now := time.Now()
myMap["now"] = now.String()
myMap["Unix"] = strconv.FormatInt(now.Unix(), 10)
myMap["UnixNano"] = strconv.FormatInt(now.UnixNano(), 10)
myMap["Format"] = now.Format("2006-01-02 15:04:05")
writer.Header().Set("content-type", "application/json")
// style1
bytes, _ := json.Marshal(myMap)
writer.Write(bytes)
// style2
//io.WriteString(writer, MapToJson(myMap))
// style3
//fmt.Fprint(writer, MapToJson(myMap))
}
func NewMap() map[string]string {
var myMap map[string]string
myMap = make(map[string]string)
return myMap
}
func MapToJson(param map[string]string) string {
dataType, _ := json.Marshal(param)
dataString := string(dataType)
return dataString
}