initial commit
This commit is contained in:
83
migration/client.go
Normal file
83
migration/client.go
Normal file
@@ -0,0 +1,83 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.gyulakerezsi.ro/migrate-github/utils"
|
||||
)
|
||||
|
||||
type client struct {
|
||||
apiURL string
|
||||
pat string
|
||||
httpClient *http.Client
|
||||
User *userResponse
|
||||
}
|
||||
|
||||
type userResponse struct {
|
||||
Username string `json:"username"`
|
||||
ID int `json:"id"`
|
||||
}
|
||||
|
||||
type migrateRequest struct {
|
||||
CloneAddr string `json:"clone_addr"`
|
||||
UID int `json:"uid"`
|
||||
RepoName string `json:"repo_name"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// Migrate will send a migrate request to the gogs server
|
||||
func (c *client) Migrate(cloneURL, description, targetName string) error {
|
||||
jsonBody, err := json.Marshal(&migrateRequest{cloneURL, c.User.ID, targetName, description})
|
||||
utils.PanicOnError(err)
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, c.apiURL+"repos/migrate", bytes.NewReader(jsonBody))
|
||||
utils.PanicOnError(err)
|
||||
|
||||
c.setHeadersOnRequest(req)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
utils.PanicOnError(err)
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("got non-success status code: %s\n==========request=========\n%+v\n=================response=============\n%+v", resp.Status, req, resp)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *client) setHeadersOnRequest(req *http.Request) {
|
||||
req.Header.Set("Authorization", "token "+c.pat)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
if req.Method == http.MethodPost {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *client) getUIDFromGogs() {
|
||||
req, err := http.NewRequest(http.MethodGet, c.apiURL+"user", http.NoBody)
|
||||
utils.PanicOnError(err)
|
||||
c.setHeadersOnRequest(req)
|
||||
|
||||
response, err := c.httpClient.Do(req)
|
||||
utils.PanicOnError(err)
|
||||
|
||||
user := userResponse{}
|
||||
utils.UnmarshalFromResponse(response, &user)
|
||||
c.User = &user
|
||||
}
|
||||
|
||||
// NewClient creates new migrationClient
|
||||
func NewClient(baseURL, pat string) *client {
|
||||
client := &client{}
|
||||
client.apiURL = strings.TrimRight(baseURL, "/") + "/api/v1/"
|
||||
client.pat = pat
|
||||
client.httpClient = &http.Client{}
|
||||
client.getUIDFromGogs()
|
||||
|
||||
return client
|
||||
}
|
||||
Reference in New Issue
Block a user