@@ -9,9 +9,11 @@ package k2
99
1010import (
1111 "context"
12+ "encoding/json"
1213 "fmt"
1314 "github.com/opendevops-cn/codo-golang-sdk/client/xhttp"
1415 "github.com/opendevops-cn/codo-golang-sdk/consts"
16+ "io"
1517 "net/http"
1618)
1719
@@ -27,6 +29,13 @@ type AuthConfig struct {
2729 cookies []* http.Cookie
2830}
2931
32+ type Response struct {
33+ Code uint32 `json:"code"`
34+ Msg string `json:"msg"`
35+ Reason string `json:"reason"`
36+ Data map [string ]string `json:"data"`
37+ }
38+
3039func NewNoAuthConfig (url string , client xhttp.IClient ) * NoAuthConfig {
3140 return & NoAuthConfig {
3241 url : url ,
@@ -46,22 +55,42 @@ func NewAuthConfig(url, authKey string, client xhttp.IClient) *AuthConfig {
4655 }
4756}
4857
49- func ( x * NoAuthConfig ) GetConfig ( ctx context.Context ) ( * http.Response , error ) {
50- req , err := http .NewRequestWithContext (ctx , "GET" , x . url , nil )
58+ func getConfig ( ctx context.Context , client xhttp. IClient , url string , cookies [] * http.Cookie ) ( map [ string ] string , error ) {
59+ req , err := http .NewRequestWithContext (ctx , "GET" , url , nil )
5160 if err != nil {
5261 return nil , fmt .Errorf ("build request err: %w" , err )
5362 }
54- return x .client .Do (ctx , req )
55- }
63+ for _ , cookie := range cookies {
64+ req .AddCookie (cookie )
65+ }
66+ resp , err := client .Do (ctx , req )
67+ if err != nil {
68+ return nil , fmt .Errorf ("do request err: %w" , err )
69+ }
70+ defer resp .Body .Close ()
5671
57- func (x * AuthConfig ) GetConfig (ctx context.Context ) (* http.Response , error ) {
58- req , err := http .NewRequestWithContext (ctx , "GET" , x .url , nil )
72+ if resp .StatusCode != http .StatusOK {
73+ return nil , fmt .Errorf ("response status code %d" , resp .StatusCode )
74+ }
75+ body , err := io .ReadAll (resp .Body )
5976 if err != nil {
60- return nil , fmt .Errorf ("build request err: %w" , err )
77+ return nil , fmt .Errorf ("read response body err: %w" , err )
6178 }
62- // 自动添加统一设置的 Cookie
63- for _ , cookie := range x .cookies {
64- req .AddCookie (cookie )
79+
80+ var apiResp Response
81+ if err := json .Unmarshal (body , & apiResp ); err != nil {
82+ return nil , fmt .Errorf ("unmarshal body err: %w" , err )
83+ }
84+ if apiResp .Code != consts .CodoAPISuccessCode {
85+ return nil , fmt .Errorf ("response code %d" , apiResp .Code )
6586 }
66- return x .client .Do (ctx , req )
87+ return apiResp .Data , nil
88+ }
89+
90+ func (x * NoAuthConfig ) GetConfig (ctx context.Context ) (map [string ]string , error ) {
91+ return getConfig (ctx , x .client , x .url , nil )
92+ }
93+
94+ func (x * AuthConfig ) GetConfig (ctx context.Context ) (map [string ]string , error ) {
95+ return getConfig (ctx , x .client , x .url , x .cookies )
6796}
0 commit comments