๊ธฐ์กด cli๋ฅผ ์ฌ์ฉํ๋ค. https://teamsmiley.gitbook.io/devops/go-lang/create-cli
package httpApi
import (
"context"
"log"
msal "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
"github.com/spf13/viper"
)
const scope = "api://xxxxx/.default"
const clientID = "xxxxx"
func getSecret() string {
sec := viper.GetString("AZURE_SECRET")
if sec == "" {
log.Fatalf("AZURE_SECRET is missing, please configure it myctl configure --secret <secret>")
}
return sec
}
type tokenProvider struct{}
func (t *tokenProvider) OAuthToken() string {
clientCredential, err := msal.NewCredFromSecret(getSecret())
if err != nil {
log.Fatalf("Couldn't create client app (%s)", err)
}
app, err := msal.New(clientID, clientCredential, func(o *msal.Options) {
o.Authority = "https://login.microsoftonline.com/xxxxxxx"
})
if err != nil {
log.Fatalf("Couldn't get application (%s)", err)
}
ctx := context.Background()
token, err := app.AcquireTokenByCredential(ctx, []string{
scope,
})
if err != nil {
log.Fatalf("Error getting token (%s)", err)
}
return token.AccessToken
}
xxxx๋ ๋ถ๋ถ์ ์ ๋ถ ์์ ํด์ค๋ค.
์ด์ http ๋ฆฌํ์คํธ๋ฅผ ๋ณด๋ด๊ธฐ ์ ์ ํธ์ถํด์ ํ ํฐ์ ๋ง๋ ํ ํ ํฐ์ http ๋ฆฌํ์คํธ์ ๋ฃ์ด์ฃผ๋ฉด ๋๋ค.
package httpApi
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// json ์ ๋ง๋ค์ด์ค๋ค.
type ServerResponse struct {
Id string `json:"id"`
Memo string `json:"memo"`
Cpu string `json:"cpu"`
Memory *int `json:"memory"`
CpuModelName string `json:"cpuModelName"`
}
func GetServer(query string) []ServerResponse {
searchApi := "https://api.xxx.com/servers"
oauthTokenProvider := new(tokenProvider) // auth ์์ฑ
t := oauthTokenProvider.OAuthToken() // ํ ํฐ ๋ฐ๊ธ
r, err := http.NewRequest(http.MethodGet, searchApi, nil) // http request ์์ฑ
if err != nil {
panic(err)
}
r.Header.Add("Content-Type", "application/json") //ํค๋์ ์ถ๊ฐ
r.Header.Add("Authorization", "Bearer " + t) //ํค๋์ ํ ํฐ ์ถ๊ฐ
// appending to existing query args
q := r.URL.Query()
q.Add("searchquery", query)
// assign encoded query string to http request
r.URL.RawQuery = q.Encode()
resp, err := http.DefaultClient.Do(r)
if err != nil {
panic(err)
}
defer resp.Body.Close()
responseBody, err := ioutil.ReadAll(resp.Body) // ์๋ต ๊ฒฐ๊ณผ ์ฝ๊ธฐ
if err != nil {
panic(err)
}
fmt.Println("status : ", resp.Status)
fmt.Println("responseBody : ", string(responseBody))
// var result Server
var jsonData []ServerResponse
err = json.Unmarshal(responseBody, &jsonData) // json ํ์ฑ
if err != nil {
fmt.Println("http response unmarshal error", err)
panic(err)
}
// fmt.Printf("result : %+v", jsonData) //๊ฒฐ๊ณผ ํ์ธ
return jsonData
}
์ด์ myctl์ ์ฌ์ฉํ๋ฉด ์ธ์ ๋ ํ ํฐ์ ๋ฐ์์์ ๊ทธ ํ ํฐ์ ์ด์ฉํ์ฌ api์ ์์ฒญํ ์ ์๋ค.
์ด๊ฑธ ์ฌ์ฉํ๋ฉด ์ด์ api์ ๋ฐ์ดํฐ๋ฅผ ์ฝ์์๋ ์ธ์๋ ์๊ฒ ๋๋ค.