寒武纪启智octopus获取token

This commit is contained in:
tzwang 2023-03-30 15:28:37 +08:00
parent 31ab769516
commit 87cf22db9e
2 changed files with 79 additions and 0 deletions

View File

@ -0,0 +1,64 @@
package common
import (
"bytes"
"encoding/json"
"io"
"log"
"net/http"
"time"
)
const (
Username = "c2net2@pcl.ac.cn"
Password = "c2net123"
TokenUrl = "http://192.168.242.41:8001/openaiserver/v1/authmanage/token"
Success = 200
)
var (
token, expiredAt = GenerateToken()
login = Login{
Username: Username,
Password: Password,
}
)
func GenerateToken() (string, time.Time) {
jsonStr, _ := json.Marshal(login)
req_url, err := http.NewRequest("POST", TokenUrl, bytes.NewBuffer(jsonStr))
if err != nil {
log.Fatal(err)
}
defer req_url.Body.Close()
c := http.Client{Timeout: time.Duration(3) * time.Second}
respUrl, err := c.Do(req_url)
if err != nil {
log.Fatal(err)
}
if respUrl.StatusCode != Success {
panic("获取token失败")
}
defer respUrl.Body.Close()
var loginResp LoginResp
result, _ := io.ReadAll(respUrl.Body)
json.Unmarshal(result, &loginResp)
var d time.Duration
d = time.Second * time.Duration(loginResp.Payload.Expiration)
return loginResp.Payload.Token, time.Now().Add(d)
}
func GetToken() string {
if time.Now().After(expiredAt) {
token, expiredAt = GenerateToken()
}
return token
}

View File

@ -0,0 +1,15 @@
package common
type Login struct {
Username string `json:"username"`
Password string `json:"password"`
}
type LoginResp struct {
Success bool `json:"success"`
Payload struct {
Token string `json:"token"`
Expiration int `json:"expiration"`
} `json:"payload"`
Error interface{} `json:"error"`
}