|
- package main
-
- import (
- "crypto/sha1"
- "fmt"
- "log"
- "net/http"
- "net/http/httputil"
- "net/url"
- "sort"
- "strings"
- )
-
- func main() {
- if readConfig() != nil {
- log.Fatal("unable to read config, program quit")
- return
- }
-
- Decode("SS")
- return
- //setup handler
- http.HandleFunc("/", webrootHandler)
- http.HandleFunc("/api", apiV1Main)
-
- //http.ListenAndServe("127.0.0.1:65500", nil)
- //CreateDefaultMenu()
- http.ListenAndServe(":65500", nil)
- }
-
- //apiV1Main version 1 main entry for all wechat callbacks
- //
- func apiV1Main(w http.ResponseWriter, r *http.Request) {
- logRequestDebug(httputil.DumpRequest(r, true))
-
- switch r.Method {
- case "POST":
- answerWechatPost(w, r)
- case "GET":
- answerInitialAuth(w, r)
- default:
- log.Fatalln("Unhandled HTTP %s", r.Method)
- fmt.Fprintf(w, "Protocol Error: Expect GET or POST only")
- }
- }
-
- //
- //answerInitialAuth, when wechat first verify our URL for API hooks
- //
- func answerInitialAuth(w http.ResponseWriter, r *http.Request) {
- rq := r.URL.RawQuery
- m, _ := url.ParseQuery(rq)
-
- echostr, eok := m["echostr"]
- if checkSignature(r) && eok {
- fmt.Fprintf(w, echostr[0])
- } else {
- fmt.Fprintf(w, "wtf is wrong with the Internet")
- }
- }
-
- //answerWechatPost distribute PostRequest according to xml body info
- //
- func answerWechatPost(w http.ResponseWriter, r *http.Request) {
- return
- }
-
- //
- func checkSignature(r *http.Request) bool {
- rq := r.URL.RawQuery
- m, _ := url.ParseQuery(rq)
-
- signature, sok := m["signature"]
- timestamp, tok := m["timestamp"]
- nonce, nok := m["nonce"]
- token := APIConfig.Token
- if sok && tok && nok {
- //sort token, timestamp, nonce and join them
- strs := []string{token, timestamp[0], nonce[0]}
- sort.Strings(strs)
- s := strings.Join(strs, "")
-
- //calculate sha1
- h := sha1.New()
- h.Write([]byte(s))
- calculated := fmt.Sprintf("%x", h.Sum(nil))
- return signature[0] == calculated
- }
- return false
- }
-
- func checkSignature1() bool {
- s1 := "e39de9f2e28079c01ebb4b803dfc3442b819545c"
- t1 := "1492970761"
- n1 := "1850971833"
- token := APIConfig.Token
-
- strs := []string{token, t1, n1}
- sort.Strings(strs)
- s := strings.Join(strs, "")
-
- h := sha1.New()
- h.Write([]byte(s))
- us := fmt.Sprintf("%x", h.Sum(nil))
- return s1 == us
- }
-
- //webrootHandler sending contents to client when request "/"
- // essentially to prove the webserver is still alive
- // echo query string to the client
- func webrootHandler(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
- rq := r.URL.RawQuery
- m, _ := url.ParseQuery(rq)
- for index, element := range m {
- fmt.Fprintf(w, "\r\n%s => %s", index, element)
- }
- logRequestDebug(httputil.DumpRequest(r, true))
-
- }
-
- func logRequestDebug(data []byte, err error) {
- if err == nil {
- fmt.Printf("%s\n\n", data)
- } else {
- log.Fatalf("%s\n\n", err)
- }
- }
|