這個(gè)不是全部的代碼哦,只是一個(gè)演示可以驗(yàn)證跟接受post傳過(guò)來(lái)的消息并且能返回消息,中間的回復(fù)邏輯就待需要各位同志們自己寫(xiě)了哈
復(fù)制代碼 代碼如下:
/*
*@go語(yǔ)言實(shí)現(xiàn)公眾平臺(tái)
*/
package main
import (
"crypto/sha1"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"sort"
"strings"
"time"
)
type Request struct {
ToUserName string
FromUserName string
CreateTime time.Duration
MsgType string
Content string
MsgId int
}
type Response struct {
ToUserName string `xml:"xml>ToUserName"`
FromUserName string `xml:"xml>FromUserName"`
CreateTime string `xml:"xml>CreateTime"`
MsgType string `xml:"xml>MsgType"`
Content string `xml:"xml>Content"`
MsgId int `xml:"xml>MsgId"`
}
func str2sha1(data string) string {
t := sha1.New()
io.WriteString(t, data)
return fmt.Sprintf("%x", t.Sum(nil))
}
func action(w http.ResponseWriter, r *http.Request) {
postedMsg, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
}
r.Body.Close()
v := Request{}
xml.Unmarshal(postedMsg, v)
if v.MsgType == "text" {
v := Request{v.ToUserName, v.FromUserName, v.CreateTime, v.MsgType, v.Content, v.MsgId}
output, err := xml.MarshalIndent(v, " ", " ")
if err != nil {
fmt.Printf("error:%v\n", err)
}
fmt.Fprintf(w, string(output))
} else if v.MsgType == "event" {
Content := `"歡迎關(guān)注
我的微信"`
v := Request{v.ToUserName, v.FromUserName, v.CreateTime, v.MsgType, Content, v.MsgId}
output, err := xml.MarshalIndent(v, " ", " ")
if err != nil {
fmt.Printf("error:%v\n", err)
}
fmt.Fprintf(w, string(output))
}
}
func checkSignature(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
var token string = "你的token"
var signature string = strings.Join(r.Form["signature"], "")
var timestamp string = strings.Join(r.Form["timestamp"], "")
var nonce string = strings.Join(r.Form["nonce"], "")
var echostr string = strings.Join(r.Form["echostr"], "")
tmps := []string{token, timestamp, nonce}
sort.Strings(tmps)
tmpStr := tmps[0] + tmps[1] + tmps[2]
tmp := str2sha1(tmpStr)
if tmp == signature {
fmt.Fprintf(w, echostr)
}
}
func main() {
http.HandleFunc("/check", checkSignature)
http.HandleFunc("/", action)
http.ListenAndServe(":8080", nil)
}
您可能感興趣的文章:- Go語(yǔ)言中的Array、Slice、Map和Set使用詳解
- Go語(yǔ)言實(shí)現(xiàn)簡(jiǎn)單的一個(gè)靜態(tài)WEB服務(wù)器
- GO語(yǔ)言并發(fā)編程之互斥鎖、讀寫(xiě)鎖詳解
- ubuntu下搭建Go語(yǔ)言(golang)環(huán)境
- GO語(yǔ)言(golang)基礎(chǔ)知識(shí)
- 淺談Go語(yǔ)言中字符串和數(shù)組
- GO 語(yǔ)言學(xué)習(xí)指南