【Golang】我的第一个Golang Web程序

  • 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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值