Patrick Peng Sun 8 роки тому
коміт
611fba2b0c
3 змінених файлів з 157 додано та 0 видалено
  1. +18
    -0
      .vscode/launch.json
  2. +30
    -0
      listen.go
  3. +109
    -0
      main.go

+ 18
- 0
.vscode/launch.json Переглянути файл

@@ -0,0 +1,18 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"remotePath": "",
"port": 2345,
"host": "127.0.0.1",
"program": "${fileDirname}",
"env": {},
"args": [],
"showLog": true
}
]
}

+ 30
- 0
listen.go Переглянути файл

@@ -0,0 +1,30 @@
package main

import (
"fmt"
"net/http"
"net/url"
)

func handler(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, "<br>%s => %s", index, element)
}
// fmt.Fprintf(w, m["k"][0]);
}

func wechat_auth_setup_handler(w http.ResponseWriter, r *http.Request) {
rq := r.URL.RawQuery
m, _ := url.ParseQuery(rq)
fmt.Fprintf(w, m["echostr"][0])
}

func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/api", wechat_auth_setup_handler)
//http.ListenAndServe("127.0.0.1:65500", nil)
http.ListenAndServe(":65500", nil)
}

+ 109
- 0
main.go Переглянути файл

@@ -0,0 +1,109 @@
//
// {"access_token":"s0wf65p-KMzvYtH8qPu2qSX_EXLE2NaBgFHl7MZwedc7Kv_hdO0FG1QeUmBYJAGmQqJinPwFr67MRZwJee4rDnGVwhbuIfKs29N4ZJSXFP8fbAheuas08UuRe13UsdCtWSMcAFAGCW","expires_in":7200}
//
package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"time"
)

//SaveToPath : where the authtoken json file is stored
const SaveToPath = "/tmp/wechat_hitxy_token"

type authToken struct {
AccessToken string `json:"access_token"`
ExpireIn int64 `json:"expires_in"`
Time time.Time `json:"created_at"`
}

func main2() {
e, _ := renewAuthtoken()
t, _ := readTokenFromFile("/tmp/wechat_hitxy_token")
fmt.Println(isAuthTokenExpired(t), e)
}

func debug(data []byte, err error) {
if err == nil {
fmt.Printf("%s\n\n", data)
} else {
log.Fatalf("%s\n\n", err)
}
}

func isAuthTokenExpired(t authToken) bool {
seconds := fmt.Sprintf("%ds", t.ExpireIn) //7200s
duration, _ := time.ParseDuration(seconds)
expire := t.Time.Add(duration)
return time.Now().After(expire)
}

func writeTokenToFile(body []byte, path string) {
log.Printf("writing authtoke to %s\r\n", path)
ioutil.WriteFile(path, body, 0600)
}

func readTokenFromFile(path string) (authToken, error) {
var m authToken
log.Printf("read authtoke from %s\r\n", path)
body, err := ioutil.ReadFile(path)
json.Unmarshal(body, &m)
return m, err
}

func renewAuthtoken() (authToken, error) {
//url := "http://vimeo.com/api/v2/brad/info.json"
url := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx876e233fde456b7b&secret=4a91aa328569b10a9fb97adeb8b0af58"
var myClient = &http.Client{Timeout: 20 * time.Second}
r, err := myClient.Get(url)
if err != nil {
return authToken{}, err
}
defer r.Body.Close()

var t authToken
err = json.NewDecoder(r.Body).Decode(&t)

if err != nil {
return authToken{}, err
}

t.Time = time.Now()
b, _ := json.Marshal(&t)
writeTokenToFile(b, SaveToPath)
return t, nil
}

//debugged http response
func dummy() {
var body []byte
var response *http.Response
var request *http.Request
url := "http://vimeo.com/api/v2/brad/info.json"

request, err := http.NewRequest("GET", url, nil)
if err == nil {
request.Header.Add("Content-Type", "application/json")
debug(httputil.DumpRequestOut(request, true))
response, err = (&http.Client{}).Do(request)
}

if err == nil {
defer response.Body.Close()
debug(httputil.DumpResponse(response, true))
body, err = ioutil.ReadAll(response.Body)
//json.NewDecoder(response.Body).Decode(m)
}

if err == nil {
writeTokenToFile(body, "/tmp/wechat_hitxy_token")
//m.Time = time.Now()
} else {
log.Fatalf("ERROR: %s", err)
}
}

Завантаження…
Відмінити
Зберегти