Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
Xavier-Lam committed Jul 20, 2023
0 parents commit 2d1ac23
Show file tree
Hide file tree
Showing 16 changed files with 1,308 additions and 0 deletions.
23 changes: 23 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Go

on: [push, pull_request]

jobs:
test:
name: Test
runs-on: ubuntu-latest

# strategy set
strategy:
matrix:
go: [ '1.17','1.18','1.19','1.20' ]

steps:
- uses: actions/checkout@v3
- name: Set up Go 1.x
uses: actions/setup-go@v4
with:
go-version: ${{ matrix.go }}
id: go
- name: Test
run: go test -v -race ./...
21 changes: 21 additions & 0 deletions LICENCE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2023 Xavier-Lam

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
41 changes: 41 additions & 0 deletions README.en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# go-wechat

**go-wechat** is a Go package that provides a client for interacting with the WeChat API. It allows you to send API requests to WeChat and handle the response. Currently, it supports only API requests for [Official account](https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html) and [Mini program](https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/).

[中文版](README.md)

Features:

* Automatically store and update credentials
* Automatically refresh credential and retry after a credential corrupted
* Full unittest coverage
* Easy use and flexible APIs

## Quickstart
* Basic usage

package main

import (
"github.com/Xavier-Lam/go-wechat"
"github.com/Xavier-Lam/go-wechat/caches"
"github.com/Xavier-Lam/go-wechat/client"
)

func main() {
auth := wechat.NewAuth("appId", "appSecret")
cache := caches.NewDummyCache()
conf := &client.Config{Cache: cache}
c := client.New(auth, conf)
data := map[string]interface{}{
"scene": "value1",
"width": 430,
}
resp, err := c.PostJson("/wxa/getwxacodeunlimit", data, true)
}

* Get latest access token

c := client.New(auth, conf)
token, err := c.GetAccessToken()
ak := token.GetAccessToken()
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# go-wechat

**go-wechat** 是一个Go拓展,提供了一个用于与微信API进行交互的客户端。它允许您向微信发送API请求并处理响应。目前支持[公众号](https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html)[小程序](https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/).

**[English Readme](README.en.md)**

功能:

* 自动存储和更新Access token
* Access token失效后自动刷新并重试
* 完整的单元测试
* 易用灵活的接口

## 快速开始
* 接口调用

package main

import (
"github.com/Xavier-Lam/go-wechat"
"github.com/Xavier-Lam/go-wechat/caches"
"github.com/Xavier-Lam/go-wechat/client"
)

func main() {
auth := wechat.NewAuth("appId", "appSecret")
cache := caches.NewDummyCache()
conf := &client.Config{Cache: cache}
c := client.New(auth, conf)
data := map[string]interface{}{
"scene": "value1",
"width": 430,
}
resp, err := c.PostJson("/wxa/getwxacodeunlimit", data, true)
}

* 获取最新token

c := client.New(auth, conf)
token, err := c.GetAccessToken()
ak := token.GetAccessToken()
33 changes: 33 additions & 0 deletions auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package wechat

// Auth represents the authentication interface
type Auth interface {
// AppId of your WeChat application
GetAppId() string
// AppSecret of your WeChat application
GetAppSecret() string
}

// auth implements the Auth interface
type auth struct {
appId string
appSecret string
}

// NewAuth creates a new instance of Auth
func NewAuth(appId string, appSecret string) Auth {
return &auth{
appId: appId,
appSecret: appSecret,
}
}

// GetAppID returns the AppId
func (a *auth) GetAppId() string {
return a.appId
}

// GetAppSecret returns the AppSecret
func (a *auth) GetAppSecret() string {
return a.appSecret
}
24 changes: 24 additions & 0 deletions caches/cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package caches

import "errors"

const (
CacheDefaultKeyPrefix = "wx:"

CacheBizAccessToken = "ak"
CacheBizJSTicket = "js_ticket"
)

var CacheErrorKeyNotFound = errors.New("Key not found in cache")

type Cache interface {
// Get retrieves the value associated with the given appId and biz from the cache.
// If successful, it returns the value as an interface{} and nil error.
// If no value is found or an error occurs, it returns nil value and `CacheErrorKeyNotFound`.
Get(appId string, biz string) (interface{}, error)

// Set stores the given value in the cache with the provided expiration time for the specified appId and biz.
// If successful, it returns nil error.
// If an error occurs during the storing process, it returns an error containing details of the failure.
Set(appId string, biz string, value interface{}, expiresIn int) error
}
84 changes: 84 additions & 0 deletions caches/cache_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package caches_test

import (
"testing"
"time"

"github.com/Xavier-Lam/go-wechat/caches"
"github.com/stretchr/testify/assert"
)

type CacheFactory func() caches.Cache

func TestDummyCache(t *testing.T) {
testCache(t, func() caches.Cache {
return caches.NewDummyCache()
})
}

// func TestRedisCache(t *testing.T) {
// testCache(t, func() w.Cache {
// s, err := miniredis.Run()
// assert.NoError(t, err)
// r := redis.NewClient(&redis.Options{
// Addr: s.Addr(),
// })
// return caches.NewRedisCache(r, "")
// })
// }

func testCache(t *testing.T, f CacheFactory) {
testCacheGet(t, f)
testCacheSet(t, f)
}

func testCacheGet(t *testing.T, f CacheFactory) {
cache := f()

// Set a value in the cache
appId := "myAppId"
biz := "myBiz"
value := "myValue"
expiresIn := 1 // seconds

nilValue, err := cache.Get(appId, biz)
assert.ErrorIs(t, err, caches.CacheErrorKeyNotFound)
assert.Nil(t, nilValue, "Expected nil value")

err = cache.Set(appId, biz, value, expiresIn)
assert.NoError(t, err, "Failed to set value in cache")

// Get the value from the cache
got, err := cache.Get(appId, biz)
assert.NoError(t, err, "Failed to get value from cache")

// Check that the retrieved value matches the expected value
assert.Equal(t, value, got, "Retrieved value does not match expected value")

// Wait for the value to expire
time.Sleep(time.Duration(expiresIn+1) * time.Second)

// Get the expired value from the cache
gotExpired, err := cache.Get(appId, biz)
assert.ErrorIs(t, err, caches.CacheErrorKeyNotFound)
assert.Nil(t, gotExpired, "Expected nil value")
}

func testCacheSet(t *testing.T, f CacheFactory) {
cache := f()

// Set a value in the cache
appId := "myAppId"
biz := "myBiz"
value := "myValue"
expiresIn := 10 // seconds
err := cache.Set(appId, biz, value, expiresIn)
assert.NoError(t, err, "Failed to set value in cache")

// Get the value from the cache
got, err := cache.Get(appId, biz)
assert.NoError(t, err, "Failed to get value from cache")

// Check that the retrieved value matches the expected value
assert.Equal(t, value, got, "Retrieved value does not match expected value")
}
50 changes: 50 additions & 0 deletions caches/dummy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package caches

import (
"time"
)

type cacheItem struct {
Value interface{}
ExpiresAt time.Time
}

type dummyCache struct {
cache map[string]cacheItem
}

func NewDummyCache() Cache {
return &dummyCache{
cache: make(map[string]cacheItem),
}
}

func (c *dummyCache) Get(appId string, biz string) (interface{}, error) {
key := getKey(appId, biz)
item, ok := c.cache[key]
if !ok {
return nil, CacheErrorKeyNotFound
}

if item.ExpiresAt.Before(time.Now()) {
delete(c.cache, key)
return nil, CacheErrorKeyNotFound
}

return item.Value, nil
}

func (c *dummyCache) Set(appId string, biz string, value interface{}, expiresIn int) error {
key := getKey(appId, biz)
expiresAt := time.Now().Add(time.Duration(expiresIn) * time.Second)
item := cacheItem{
Value: value,
ExpiresAt: expiresAt,
}
c.cache[key] = item
return nil
}

func getKey(appId, biz string) string {
return appId + ":" + biz
}
26 changes: 26 additions & 0 deletions client/cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package client

import (
"errors"
)

const (
CacheDefaultKeyPrefix = "wx:"

CacheBizAccessToken = "ak"
CacheBizJSTicket = "js_ticket"
)

var CacheErrorKeyNotFound = errors.New("Key not found in cache")

type Cache interface {
// Get retrieves the value associated with the given appId and biz from the cache.
// If successful, it returns the value as an interface{} and nil error.
// If no value is found or an error occurs, it returns nil value and `CacheErrorKeyNotFound`.
Get(appId string, biz string) (interface{}, error)

// Set stores the given value in the cache with the provided expiration time for the specified appId and biz.
// If successful, it returns nil error.
// If an error occurs during the storing process, it returns an error containing details of the failure.
Set(appId string, biz string, value interface{}, expiresIn int) error
}
Loading

0 comments on commit 2d1ac23

Please sign in to comment.