Golang implementation of WeChat public platform API engine development model

Source: Internet
Author: User
Tags sha1
This is a creation in Article, where the information may have evolved or changed.
/* * @author spinach June * @Version 0.2 * @time 2013-10-29 * @golang implement the public Platform API engine development mode *@ Qingdao Programmer subscription Number Qdprogrammer * @Golang subscription number Gostock *@ about Qingdao Programmer's technology, entrepreneurship, life sharing. *@ Open Source https://github.com/philsong/*/package mainimport ("Crypto/sha1" "Encoding/xml" "FMT" "io" "io/ioutil" "Log" "net/ http "Sort" "strings" "Time") const (TOKEN = "Gostock" text = "text" location = "Location" image = "image" Link = " Link "event =" event "music =" Music "news =" News ") type msgbase struct {tousername stringfromusername Stringcrea Tetime time. Durationmsgtype stringcontent string}type Request struct {xmlname XML. Name ' xml: ' xml ' ' msgbase//Base structlocation_x, location_y Float32scale Intlabe L stringpicurl stringmsgid int}type Response struct {xmlname XML. Name ' xml: ' xml ' ' msgbasearticlecount int ' xml: ', Omitempty ' articles []*item ' xml: ' Articles>item,omitempty ' ' FUNCF Lag Int}type item struct {Xmlname XML. Name ' xml: ' item ' ' Title stringdescription stringpicurl stringurl string}func weixinevent (w http. Responsewriter, R *http. Request) {if Weixinchecksignature (W, r) = = False {fmt. Println ("Auth failed, attached?") Return}fmt. Println ("auth success, parse POST") defer r.body.close () Body, err: = Ioutil. ReadAll (r.body) if err! = Nil {log. Fatal (Err) return}fmt. Println (String (body)) var wreq *requestif wreq, err = decoderequest (body); Err! = Nil {log. Fatal (Err) return}wresp, err: = Dealwith (wreq) if err! = Nil {log. Fatal (Err) return}data, err: = Wresp. Encode () if err! = Nil {fmt. Printf ("error:%v\n", err) return}fmt. Println (String (data)) FMT. fprintf (W, string (data)) Return}func Dealwith (req *request) (resp *response, err error) {resp = Newresponse () resp. Tousername = req. Fromusernameresp.fromusername = req. Tousernameresp.msgtype = Textif req. Msgtype = = Event {if req. Content = = "Subscribe" {resp. Content = "Welcome to the subscription number Qdprogrammer, share the technology of Qingdao programmers, entrepreneurship, life." "Return resp, nil}}if req. Msgtype = = Text {if strings. Trim (Strings. ToLower (req. Content), "") = = "Help" {resp. Content = "Welcome to the subscription number Qdprogrammer, share the technology of Qingdao programmers, entrepreneurship, life." "Return resp, Nil}resp. Content = "Pro, spinach June has received your message and will reply to you as soon as possible."} else if req. Msgtype = = Image {var a itema. Description = "Ya Minute fly butterfly ... ^_^ ^_^ 1024 you know "a.title =" Ya Minute fly butterfly test "A.picurl =" http://static.yaliam.com/gwz.jpg "A.url =" Http://blog.csdn.net/songbohr "Resp. Msgtype = Newsresp.articlecount = 1resp. Articles = Append (resp. Articles, &a) resp. Funcflag = 1} else {resp. Content = "No other type is currently supported"}return RESP, Nil}func Weixinauth (w http. Responsewriter, R *http. Request) {if Weixinchecksignature (W, r) = = true {var echostr string = strings. Join (r.form["Echostr"], "") fmt. fprintf (W, echostr)}}func Weixinhandler (w http. Responsewriter, R *http. Request) {if R.method = = "GET" {fmt. PRINTLN ("GET begin ...") Weixinauth (W, R) fmt. Println ("GET END ...")} else {fmt. PRINTLN ("POST begin ...") Weixinevent (W, R) fmt. Println ("POST END ...")}}func Main () {http. Handlefunc ("/check", Weixinhandler)//http. Handlefunc ("/", actION) Port: = "println" ("Listening on port", "Port", "...") Err: = http. Listenandserve (":" +port, Nil)//Set the listening port if err! = Nil {log. Fatal ("Listenandserve:", err)}}func str2sha1 (data String) string {t: = SHA1. New () Io. WriteString (t, data) return to FMT. Sprintf ("%x", T.sum (nil))}func weixinchecksignature (w http. Responsewriter, R *http. Request) bool {r.parseform () fmt. Println (R.form) var signature string = strings. Join (r.form["signature"], "") var timestamp string = strings. Join (r.form["timestamp"], "") var nonce string = strings. Join (r.form["nonce"], "") tmps: = []string{token, timestamp, Nonce}sort. Strings (tmps) Tmpstr: = Tmps[0] + tmps[1] + tmps[2]tmp: = STR2SHA1 (TMPSTR) if tmp = = Signature {return True}return False}fun c decoderequest (data []byte) (req *request, err error) {req = &request{}if err = XML. Unmarshal (data, req); Err! = Nil {return}req. Createtime *= time. Secondreturn}func Newresponse () (resp *response) {resp = &response{}resp. Createtime = time. Duration (time. Now (). Unix ()) Return}func (Resp Response) Encode () (data []byte, err Error) {resp. Createtime = time. Duration (time. Now (). Unix ()) data, err = XML. Marshal (RESP) return}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.