最近接触了一下微信公众号开发,刚好很久很久之前申请过一个公众号,看了下API文档,用go实现了一个简单的获取 access_token的功能。 下面的代码可以从微信服务器获取access_tokens,并保存在内存中,然后其他程序可以通过http请求获取到内存中的 access_token,超时的时候,还会自动重新从微信服务器获取新的access_tokens。 只需要配置 config.json文件即可,config.json和main.go文件处于同一目录层级,config.json格式文件配置如下:

{

“appid”:”XXX”,

“secret”:”XXX”,

“token”:”XXX”,

“port”:”7001”

}

其中 appid,secret以及token需要在微信公众平台获取相关信息。

port 则是你使用的监听接口,即其他人通过这个接口获取access_tokens。 获取的方式是通过浏览器访问你的 url地址+/token 后缀。

运行时,输入 go run main.go config.json 即可

代码: main.go

package main

import (

“bytes”

“encoding/json”

“io/ioutil”

“log”

“net/http”

“os”

“time”

)

const wx_params_timestamp string = “timestamp”

const wx_params_signature string = “signature”

const wx_params_nonce string = “nonce”

const wx_params_echostr string = “echostr”

const wx_access_token_key string = “access_token”

const wx_access_token_time_key string = “expires_in”

const wx_access_token_error_code string = “errcode”

const wx_access_token_error_msg string = “errmsg”

//

var wx_gzh_token_str string

var wx_gzh_appid string

var wx_gzh_secret string

var global_access_token string

var global_access_token_time_out int64

type SConsConfig struct {

Appid string `json:”appid”`

Secret string `json:”secret”`

Token string `json:”token”`

Port string `json:”port”`

}

func NewJsonStruct() *SConsConfig {

return &SConsConfig{}

}

func (jst *SConsConfig) LoadConfig(fileName string, v interface{}) {

data, err := ioutil.ReadFile(fileName)

if err != nil {

return

}

err = json.Unmarshal(data, v)

if err != nil {

return

}

}

func ParseSconsConfig(fileName string) (v SConsConfig, err error) {

JsonParse := NewJsonStruct()

v = SConsConfig{}

JsonParse.LoadConfig(fileName, &v)

return v, nil

}

type wx_access_token_center_handler struct{}

func (h *wx_access_token_center_handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

log.Println(“somebody require token”)

current_time := time.Now().Unix()

if current_time > global_access_token_time_out {

log.Println(“token timetou ,require from wx………..”)

GetAccessToken(wx_gzh_appid, wx_gzh_secret)

} else {

log.Println(“token is valid,require from local”)

}

w.Write([]byte(global_access_token))

}

func ParseTokens(str string) {

decoder := json.NewDecoder(bytes.NewBufferString(str))

decoder.UseNumber()

var result map[string]interface{}

if err := decoder.Decode(&result); err != nil {

log.Println(“json parse failed,str=”, str, “\nerr=”, err)

os.Exit(1)

}

log.Println(“parse”, str, “json”)

if _, ok := result[wx_access_token_error_code]; ok {

log.Println(“error token,code=”, result[wx_access_token_error_code])

log.Println(“errmsg=”, result[wx_access_token_error_msg])

}

access_token := result[wx_access_token_key]

access_token_value, ok := access_token.(string)

if !ok {

log.Println(“parse access_token failed,access_token=”, access_token)

}

log.Println(“access_token_value:”, access_token_value)

time_num := result[wx_access_token_time_key]

time_num_value, err := time_num.(json.Number).Int64()

if err != nil {

log.Println(“parase time_num failed,time_num=”, time_num)

}

log.Println(“time:”, time_num_value)

current_time := time.Now().Unix()

global_access_token = access_token_value

global_access_token_time_out = current_time + time_num_value

formatTimeStr := time.Unix(global_access_token_time_out, 0).Format(“2006-01-02 15:04:05”)

log.Println(“success parse json,token will be timeout at “, global_access_token_time_out, “,”, formatTimeStr)

}

func GetAccessToken(appid string, secret string) {

params := “/cgi-bin/token?grant_type=client_credential&appid=” + appid + “&secret=” + secret

urls := []string{“api.weixin.qq.com”, “api2.weixin.qq.com”, “sh.api.weixin.qq.com”, “sz.api.weixin.qq.com”, “hk.api.weixin.qq.com”}

success := false

for _, v := range urls {

url := “https://“ + v + params

resp, err := http.Get(url)

if nil != err {

log.Println(“get wx access token from “+url+” error,err=”, err)

} else {

success = true

log.Println(“get wx access token from “ + url + “ success”)

defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)

if nil != err {

log.Println(“get wx access token error,read resp body error,err=”, err)

return

}

tokenstr := string(body)

log.Println(“access_token:”, tokenstr)

ParseTokens(tokenstr)

break

}

}

if !success {

log.Println(“get wx access error from all api”)

os.Exit(1)

}

}

func InitGlobal() {

wx_gzh_appid = “”

wx_gzh_secret = “”

wx_gzh_token_str = “”

global_access_token = “”

global_access_token_time_out = 0

}

func HttpTokenServer(tokenPort string) {

http.Handle(“/token”, &wx_access_token_center_handler{})

port := “0.0.0.0:” + tokenPort

log.Println(“start listen token port:”, tokenPort)

http.ListenAndServe(port, nil)

}

func main() {

log.Println(“start gzh token center”)

log.Println(“param format: config.json”)

arg_num := len(os.Args)

if arg_num < 2 {

log.Println(“please input the port”)

os.Exit(1)

}

InitGlobal()

configFile := os.Args[1]

config, err := ParseSconsConfig(configFile)

if nil != err {

log.Println(“parse config error,err=”, err)

os.Exit(1)

}

wx_gzh_appid = config.Appid

wx_gzh_secret = config.Secret

wx_gzh_token_str = config.Token

HttpTokenServer(config.Port)

}

linux 多目录makefile,royalchen相关推荐

  1. Linux 内核顶层Makefile 详解

    目录 前602行分析 make xxx_defconfig 过程 Makefile.build 脚本分析 make 过程 built-in.o 文件编译生成过程 make zImage 过程 前几章我 ...

  2. 多目录Makefile(库及分层目录)

    本文代码虽简单,但涉及比较复杂的各种调用关系,欲研究者需有耐心及清醒头脑. 切切!背景交待: 1.正在移植U-Boot,并对其源代码进行了一些分析,感觉它的Makefile十分强劲: 2.以前写的Ma ...

  3. Linux内核中makefile有什么作用?深入解析makefile工作过程和原理

    Table of Contents Makefile 中的变量 常用的变量有以下几类: 1) 版本信息 2) CPU 体系结构:ARCH 3) 路径信息:TOPDIR, SUBDIRS 4) 内核组成 ...

  4. linux内核makefile详解,linux kernel编译Makefile和Kconfig,make menuconfig详解

    Sam需要看看2.6 kernel中USB Mouse的代码.顺便谈谈Kernel中Makefile和Kconfig文件的关系以及配合使用. 背景知识: 背景知识一:Kconfig介绍: 在#make ...

  5. spdlog linux编译出错,Linux下编写Makefile引入第三方库

    Linux下编写Makefile引入第三方库 前言:一直在使用CmakaList 生成Makefile文件,其实很少去写Makefile,但是最近帮朋友处理了一个Makefile引入第三方库的问题,就 ...

  6. 【正点原子Linux连载】第三十五章 Linux内核顶层Makefile详解 -摘自【正点原子】I.MX6U嵌入式Linux驱动开发指南V1.0

    1)实验平台:正点原子阿尔法Linux开发板 2)平台购买地址:https://item.taobao.com/item.htm?id=603672744434 2)全套实验源码+手册+视频下载地址: ...

  7. linux内核顶层Makefile详解

    文章目录 一.linux内核获取 二.linux内核初次编译 三.linux工程目录分析 1.获取源码 2.目录介绍 1.总体浏览 2.arch 目录 3.block 目录 4.crypto 目录 5 ...

  8. Linux下的makefile编写 ——陈皓《跟我一起写Makefile》学习笔记(一)

    Linux下的makefile编写 前言 本人记笔记习惯使用OneNote,在学习LinuxC++过程中发现deepin上没有大佬开发或者移植,本人技术也不精,所以决定写博客记笔记(只是习惯问题,并没 ...

  9. Linux 内核顶层 Makefile 详解

    Linux 内核获取 Linux 由 Linux 基金会管理与发布, Linux 官网为 https://www.kernel.org,所以你想获取最新的 Linux 版本就可以在这个网站上下载 最新 ...

最新文章

  1. NameServer的总控逻辑
  2. VS2010属性表的建立与灵活运用
  3. SVG脚本编程简介(转)
  4. 幼儿园计算机教师论文,幼儿园中班教师论文
  5. 【转】微信开发出现“该公众号暂时无法提供服务,请稍后再试”的坑
  6. Node.js:借助formidable文件上传
  7. iphone自适应屏幕亮度_如何降低iPhone的亮度低于iOS允许的亮度
  8. 5款创业在线学习的工具
  9. 火车头采集html文档没内容,火车头采集器:编辑任务中常见问题
  10. 去除枕头异味的两种方法
  11. 【Kotlin -- 知识点】Kotlin 中的委托
  12. python绘图报错
  13. python的pyaudio教程入门_Python豪杰物语:pyaudio的安装播放音频示例
  14. c ajax 图表,Pyechart Django:前端和后端分离(Ajax),多图表组合显示,pyechartsdjango,前后,ajax,合并,展示...
  15. 4h上手C++版Opencv
  16. 前端网页配色网站推荐
  17. NUIST第一届程序设计大赛团队赛题解
  18. 记首次参加网络安全比赛(初赛-知识竞赛,决赛-CTF夺旗赛-解题模式)
  19. 小米智能互联App__电脑发文件到手机超时错误解决办法
  20. 【OpenMV小车——第1.2篇】OpenMV主控板的简介与入门使用

热门文章

  1. 交换机应用寻找10个完美的因素
  2. Nucleus 实时操作系统中断(下)
  3. Java 遍历map
  4. 微信小程序 文字换行
  5. 前端之css基础学习(更正版)
  6. 手动添加Cookie
  7. 2022-2028年中国消防报警行业市场前瞻与投资战略规划分析报告
  8. ueeditor 百度编译器使用onchange效果
  9. hadoop2.4.1集群搭建
  10. JavaScript总结(七)