task: support api token request

pull/7/head
oscar 2022-09-22 13:56:37 +12:00
parent f25a6f7806
commit 423c0b5a37
1 changed files with 37 additions and 1 deletions

View File

@ -1,11 +1,22 @@
package tasks package tasks
import "ocl/portainer-devtool/configs" import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"ocl/portainer-devtool/configs"
)
type GenerateJwtTokenTask struct { type GenerateJwtTokenTask struct {
Config *configs.Config Config *configs.Config
} }
type GenerateJwtTokenResponse struct {
JWT string `json:"jwt"`
}
func NewGenerateJwtTokenTask(cfg *configs.Config) *GenerateJwtTokenTask { func NewGenerateJwtTokenTask(cfg *configs.Config) *GenerateJwtTokenTask {
return &GenerateJwtTokenTask{ return &GenerateJwtTokenTask{
Config: cfg, Config: cfg,
@ -13,6 +24,31 @@ func NewGenerateJwtTokenTask(cfg *configs.Config) *GenerateJwtTokenTask {
} }
func (task *GenerateJwtTokenTask) Execute() error { func (task *GenerateJwtTokenTask) Execute() error {
postBody, _ := json.Marshal(map[string]string{
"username": task.Config.LoginCredential.Username,
"password": task.Config.LoginCredential.Password,
})
responseBody := bytes.NewBuffer(postBody)
resp, err := http.Post(task.Config.LoginCredential.Address, "application/json", responseBody)
if err != nil {
return fmt.Errorf("http requset error: %s", err.Error())
}
defer resp.Body.Close()
//Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to parse the response body: %s", err.Error())
}
var ret GenerateJwtTokenResponse
err = json.Unmarshal(body, &ret)
if err != nil {
return err
}
fmt.Printf("jwt token is:\n%s\n", ret.JWT)
return nil return nil
} }