Skip to content

Instantly share code, notes, and snippets.

@rakd
Created December 18, 2017 17:03
Show Gist options
  • Save rakd/666cc57b8165798f80a086ab68cd816a to your computer and use it in GitHub Desktop.
Save rakd/666cc57b8165798f80a086ab68cd816a to your computer and use it in GitHub Desktop.
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
)
var fybsgKey, fybsgSecret string
func init() {
log.Print("fybsg.init")
fybsgKey = getEnvWithDefault("FYBSG_KEY", "")
fybsgSecret = getEnvWithDefault("FYBSG_SECRET", "")
if fybsgSecret == "" || fybsgKey == "" {
log.Fatal("fybsgKey & fybsgSecret must not be blank")
}
log.Printf("fybsgSecret=%s", fybsgSecret)
log.Printf("fybsgKey=%s", fybsgKey)
}
// getEnvWithDefault ...
func getEnvWithDefault(key string, def string) string {
v := os.Getenv(key)
if v == "" {
return def
}
return v
}
func generateHMAC(text, key string) string {
hasher := hmac.New(sha256.New, []byte(key))
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}
// generateHMAC2 ...
func generateHMAC2(msg, key string) string {
mac := hmac.New(sha256.New, []byte(key))
mac.Write([]byte(msg))
return hex.EncodeToString(mac.Sum(nil))
}
// generateHMAC3 ...
func generateHMAC3(message string, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(message))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
// generateHMAC4 ...
func generateHMAC4(message string, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(message))
return url.QueryEscape(base64.StdEncoding.EncodeToString(h.Sum(nil)))
}
func main() {
client := &http.Client{}
ts := time.Now().Unix()
log.Printf("ts=%v", ts)
values := url.Values{}
values.Add("timestamp", fmt.Sprintf("%d", ts))
urlstr := "https://www.fybsg.com/api/SGD/getaccinfo"
req, err := http.NewRequest("POST", urlstr, strings.NewReader(values.Encode()))
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("key", fybsgKey)
req.Header.Add("sig", generateHMAC(values.Encode(), fybsgSecret))
//req.Header.Add("sig", generateHMAC2(values.Encode(), fybsgSecret))
//req.Header.Add("sig", generateHMAC3(values.Encode(), fybsgSecret))
//req.Header.Add("sig", generateHMAC4(values.Encode(), fybsgSecret))
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
respBody, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.Status)
fmt.Println(string(respBody))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment