|
- package main
-
- import (
- "bytes"
- "fmt"
- "io/ioutil"
- "net/http"
- )
-
- //menu is a json definition
- var menu = []byte(`
- {
- "button":[
- {
- "type":"click",
- "name":"今日歌曲",
- "key":"V1001_TODAY_MUSIC"
- },
- {
- "name":"菜单",
- "sub_button":[
- {
- "type":"view",
- "name":"搜索",
- "url":"http://www.soso.com/"
- },
- {
- "type":"click",
- "name":"赞一下我们",
- "key":"V1001_GOOD"
- }]
- }]
- }
- `)
-
- //CreateCustomMenu bulid a menu for wechat windows
- // 3 main manu max (< 4 mandarin words)
- // 5 sub items max (< 7 mandarin words)
- //success return nil
- //error return err
- func CreateCustomMenu(m []byte) error {
- atoken, err := GetAccessToken()
- if err != nil {
- return err
- }
- url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s", atoken)
- if len(m) == 0 {
- m = menu //using default menu
- }
- return jsonPostRequest(url, m)
-
- }
-
- //CreateDefaultMenu build a menu for wechat window
- //
- func CreateDefaultMenu() error {
- var b []byte
- return CreateCustomMenu(b)
- }
-
- //jsonPostRequest perform http post request with json body
- // url is the url to post to
- // jsonBody is the payload in http post request
- func jsonPostRequest(url string, jsonBody []byte) error {
- req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
- if err != nil {
- return err
- }
- req.Header.Set("X-Custom-Header", "Patrick Sun")
- req.Header.Set("Content-Type", "application/json")
-
- client := &http.Client{}
- resp, err := client.Do(req)
-
- if err != nil {
- return err
- }
- defer resp.Body.Close()
-
- fmt.Println("response Status:", resp.Status)
- fmt.Println("response Headers:", resp.Header)
- body, _ := ioutil.ReadAll(resp.Body)
- fmt.Println("response Body:", string(body))
-
- return nil
- }
|