本文整理匯總了Golang中github.com/dghubble/sling.New函數的典型用法代碼示例。如果您正苦於以下問題:Golang New函數的具體用法?Golang New怎麽用?Golang New使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了New函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: SetRequestTemplates
func (h *Hoverfly) SetRequestTemplates(path string) (responseTemplates *matching.RequestTemplateResponsePairPayload, err error) {
conf, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
url := h.buildURL("/api/templates")
slingRequest := sling.New().Post(url).Body(strings.NewReader(string(conf)))
_, err = h.performAPIRequest(slingRequest)
if err != nil {
return nil, err
}
slingRequest = sling.New().Get(url).Body(strings.NewReader(string(conf)))
getResponse, err := h.performAPIRequest(slingRequest)
if err != nil {
return nil, err
}
requestTemplates, err := unmarshalRequestTemplates(getResponse)
if err != nil {
return nil, err
}
return requestTemplates, nil
}
示例2: SetDelays
// Set will go the state endpoint in Hoverfly, sending JSON that will set the mode of Hoverfly
func (h *Hoverfly) SetDelays(path string) (rd []ResponseDelaySchema, err error) {
conf, err := ioutil.ReadFile(path)
if err != nil {
return rd, err
}
url := h.buildURL("/api/delays")
slingRequest := sling.New().Put(url).Body(strings.NewReader(string(conf)))
slingRequest, err = h.addAuthIfNeeded(slingRequest)
if err != nil {
log.Debug(err.Error())
return rd, errors.New("Could not authenticate with Hoverfly")
}
request, err := slingRequest.Request()
if err != nil {
log.Debug(err.Error())
return rd, errors.New("Could not communicate with Hoverfly")
}
response, err := h.httpClient.Do(request)
if err != nil {
log.Debug(err.Error())
return rd, errors.New("Could not communicate with Hoverfly")
}
slingRequest = sling.New().Get(url).Body(strings.NewReader(string(conf)))
slingRequest, err = h.addAuthIfNeeded(slingRequest)
if err != nil {
log.Debug(err.Error())
return rd, errors.New("Could not authenticate with Hoverfly")
}
request, err = slingRequest.Request()
if err != nil {
log.Debug(err.Error())
return rd, errors.New("Could not communicate with Hoverfly")
}
response, err = h.httpClient.Do(request)
if err != nil {
log.Debug(err.Error())
return rd, errors.New("Could not communicate with Hoverfly")
}
apiResponse := createAPIDelaysResponse(response)
return apiResponse.Data, nil
}
示例3: ImportSimulation
func (h *Hoverfly) ImportSimulation(simulationData string) error {
url := h.buildURL("/api/records")
slingRequest := sling.New().Post(url).Body(strings.NewReader(simulationData))
slingRequest, err := h.addAuthIfNeeded(slingRequest)
if err != nil {
log.Debug(err.Error())
return errors.New("Could not authenticate with Hoverfly")
}
request, err := slingRequest.Request()
if err != nil {
log.Debug(err.Error())
return errors.New("Could not communicate with Hoverfly")
}
response, err := h.httpClient.Do(request)
if err != nil {
log.Debug(err.Error())
return errors.New("Could not communicate with Hoverfly")
}
if response.StatusCode == 401 {
return errors.New("Hoverfly requires authentication")
}
if response.StatusCode != 200 {
return errors.New("Import to Hoverfly failed")
}
return nil
}
示例4: GetMiddleware
// GetMiddle will go the middleware endpoint in Hoverfly, parse the JSON response and return the middleware of Hoverfly
func (h *Hoverfly) GetMiddleware() (string, error) {
url := h.buildURL("/api/middleware")
slingRequest := sling.New().Get(url)
slingRequest, err := h.addAuthIfNeeded(slingRequest)
if err != nil {
log.Debug(err.Error())
return "", errors.New("Could not authenticate with Hoverfly")
}
request, err := slingRequest.Request()
if err != nil {
log.Debug(err.Error())
return "", errors.New("Could not communicate with Hoverfly")
}
response, err := h.httpClient.Do(request)
if err != nil {
log.Debug(err.Error())
return "", errors.New("Could not communicate with Hoverfly")
}
if response.StatusCode == 401 {
return "", errors.New("Hoverfly requires authentication")
}
defer response.Body.Close()
middlewareResponse := h.createMiddlewareSchema(response)
return middlewareResponse.Middleware, nil
}
示例5: UpdatePetWithForm
//func (a PetApi) UpdatePetWithForm (petId int64, name string, status string) (error) {
func (a PetApi) UpdatePetWithForm(petId int64, name string, status string) error {
_sling := sling.New().Post(a.Configuration.BasePath)
// create path and map variables
path := "/v2/pet/{petId}"
path = strings.Replace(path, "{"+"petId"+"}", fmt.Sprintf("%v", petId), -1)
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
}
// accept header
accepts := []string{"application/xml", "application/json"}
for key := range accepts {
_sling = _sling.Set("Accept", accepts[key])
break // only use the first Accept
}
type FormParams struct {
name string `url:"name,omitempty"`
status string `url:"status,omitempty"`
}
_sling = _sling.BodyForm(&FormParams{name: name, status: status})
// We use this map (below) so that any arbitrary error JSON can be handled.
// FIXME: This is in the absence of this Go generator honoring the non-2xx
// response (error) models, which needs to be implemented at some point.
var failurePayload map[string]interface{}
httpResponse, err := _sling.Receive(nil, &failurePayload)
if err == nil {
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
if failurePayload != nil {
// If the failurePayload is present, there likely was some kind of non-2xx status
// returned (and a JSON payload error present)
var str []byte
str, err = json.Marshal(failurePayload)
if err == nil { // For safety, check for an error marshalling... probably superfluous
// This will return the JSON error body as a string
err = errors.New(string(str))
}
} else {
// So, there was no network-type error, and nothing in the failure payload,
// but we should still check the status code
if httpResponse == nil {
// This should never happen...
err = errors.New("No HTTP Response received.")
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
}
}
}
return err
}
示例6: newClient
func newClient(httpClient *http.Client) *client {
base := sling.New().Client(httpClient).Base(facebookAPI)
return &client{
c: httpClient,
sling: base,
}
}
示例7: GetInventory
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return map[string]int32
*/
func (a StoreApi) GetInventory() (map[string]int32, error) {
_sling := sling.New().Get(a.Configuration.BasePath)
// authentication (api_key) required
// set key with prefix in header
_sling.Set("api_key", a.Configuration.GetApiKeyWithPrefix("api_key"))
// create path and map variables
path := "/v2/store/inventory"
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
}
// accept header
accepts := []string{"application/json"}
for key := range accepts {
_sling = _sling.Set("Accept", accepts[key])
break // only use the first Accept
}
var successPayload = new(map[string]int32)
// We use this map (below) so that any arbitrary error JSON can be handled.
// FIXME: This is in the absence of this Go generator honoring the non-2xx
// response (error) models, which needs to be implemented at some point.
var failurePayload map[string]interface{}
httpResponse, err := _sling.Receive(successPayload, &failurePayload)
if err == nil {
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
if failurePayload != nil {
// If the failurePayload is present, there likely was some kind of non-2xx status
// returned (and a JSON payload error present)
var str []byte
str, err = json.Marshal(failurePayload)
if err == nil { // For safety, check for an error marshalling... probably superfluous
// This will return the JSON error body as a string
err = errors.New(string(str))
}
} else {
// So, there was no network-type error, and nothing in the failure payload,
// but we should still check the status code
if httpResponse == nil {
// This should never happen...
err = errors.New("No HTTP Response received.")
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
}
}
}
return *successPayload, err
}
示例8: GetDelays
// GetMode will go the state endpoint in Hoverfly, parse the JSON response and return the mode of Hoverfly
func (h *Hoverfly) GetDelays() (rd []ResponseDelaySchema, err error) {
url := h.buildURL("/api/delays")
slingRequest := sling.New().Get(url)
slingRequest, err = h.addAuthIfNeeded(slingRequest)
if err != nil {
log.Debug(err.Error())
return rd, errors.New("Could not authenticate with Hoverfly")
}
request, err := slingRequest.Request()
if err != nil {
log.Debug(err.Error())
return rd, errors.New("Could not communicate with Hoverfly")
}
response, err := h.httpClient.Do(request)
if err != nil {
log.Debug(err.Error())
return rd, errors.New("Could not communicate with Hoverfly")
}
defer response.Body.Close()
apiResponse := createAPIDelaysResponse(response)
return apiResponse.Data, nil
}
示例9: LoginUser
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
* @return string
*/
func (a UserApi) LoginUser(username string, password string) (string, error) {
_sling := sling.New().Get(a.Configuration.BasePath)
// create path and map variables
path := "/v2/user/login"
_sling = _sling.Path(path)
// add default headers if any
for key := range a.Configuration.DefaultHeader {
_sling = _sling.Set(key, a.Configuration.DefaultHeader[key])
}
type QueryParams struct {
Username string `url:"username,omitempty"`
Password string `url:"password,omitempty"`
}
_sling = _sling.QueryStruct(&QueryParams{Username: username, Password: password})
// accept header
accepts := []string{"application/xml", "application/json"}
for key := range accepts {
_sling = _sling.Set("Accept", accepts[key])
break // only use the first Accept
}
var successPayload = new(string)
// We use this map (below) so that any arbitrary error JSON can be handled.
// FIXME: This is in the absence of this Go generator honoring the non-2xx
// response (error) models, which needs to be implemented at some point.
var failurePayload map[string]interface{}
httpResponse, err := _sling.Receive(successPayload, &failurePayload)
if err == nil {
// err == nil only means that there wasn't a sub-application-layer error (e.g. no network error)
if failurePayload != nil {
// If the failurePayload is present, there likely was some kind of non-2xx status
// returned (and a JSON payload error present)
var str []byte
str, err = json.Marshal(failurePayload)
if err == nil { // For safety, check for an error marshalling... probably superfluous
// This will return the JSON error body as a string
err = errors.New(string(str))
}
} else {
// So, there was no network-type error, and nothing in the failure payload,
// but we should still check the status code
if httpResponse == nil {
// This should never happen...
err = errors.New("No HTTP Response received.")
} else if code := httpResponse.StatusCode; 200 > code || code > 299 {
err = errors.New("HTTP Error: " + string(httpResponse.StatusCode))
}
}
}
return *successPayload, err
}
示例10: GetSimulation
func (s *SpectoLab) GetSimulation(simulation Simulation, overrideHost string) ([]byte, error) {
var url string
if len(overrideHost) > 0 {
url = s.buildURL(fmt.Sprintf("/api/v1/users/%v/simulations/%v/versions/%v/data?override-host=%v", simulation.Vendor, simulation.Name, simulation.Version, overrideHost))
} else {
url = s.buildURL(fmt.Sprintf("/api/v1/users/%v/simulations/%v/versions/%v/data", simulation.Vendor, simulation.Name, simulation.Version))
}
request, err := sling.New().Get(url).Add("Authorization", s.buildAuthorizationHeaderValue()).Add("Content-Type", "application/json").Request()
if err != nil {
log.Debug(err.Error())
return nil, errors.New("Could not create a request to SpectoLab")
}
response, err := http.DefaultClient.Do(request)
if err != nil {
log.Debug(err.Error())
return nil, errors.New("Could not communicate with SpectoLab")
}
defer response.Body.Close()
if response.StatusCode != 200 {
return nil, errors.New("Simulation not found in SpectoLab")
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Debug(err.Error())
return nil, errors.New("Could not pull simulation from SpectoLab")
}
return body, nil
}
示例11: UserGet
func UserGet(userId int) (user User, err error) {
params := &UserGetParams{UserIds: strconv.Itoa(userId), Version: apiVersion, Fields: "photo_100,status"}
response := new(UserGetResponse)
_, err = sling.New().Get(path + "users.get").QueryStruct(params).ReceiveSuccess(response)
user = response.Users[0]
return
}
示例12: UploadSimulation
func (s *SpectoLab) UploadSimulation(simulation Simulation, data []byte) (bool, error) {
err := s.CreateSimulation(simulation)
if err != nil {
log.Debug(err)
return false, errors.New("Unable to create a simulation on SpectoLab")
}
url := s.buildURL(fmt.Sprintf("/api/v1/users/%v/simulations/%v/versions/%v/data", simulation.Vendor, simulation.Name, simulation.Version))
request, err := sling.New().Put(url).Add("Authorization", s.buildAuthorizationHeaderValue()).Add("Content-Type", "application/json").Body(strings.NewReader(string(data))).Request()
if err != nil {
log.Debug(err)
return false, errors.New("Could not create a request to check API key against SpectoLab")
}
response, err := http.DefaultClient.Do(request)
if err != nil {
log.Debug(err)
return false, errors.New("Could not communicate with SpectoLab")
}
defer response.Body.Close()
return response.StatusCode >= 200 && response.StatusCode <= 299, nil
}
示例13: ProjectsPost
//Create a new project.
//Implementation Notes
//This endpoint is for user to create a new project.
//@param project New created project.
//@return void
//func (a HarborAPI) ProjectsPost (prjUsr UsrInfo, project Project) (int, error) {
func (a HarborAPI) ProjectsPost(prjUsr UsrInfo, project Project) (int, error) {
_sling := sling.New().Post(a.basePath)
// create path and map variables
path := "/api/projects"
_sling = _sling.Path(path)
// accept header
accepts := []string{"application/json", "text/plain"}
for key := range accepts {
_sling = _sling.Set("Accept", accepts[key])
break // only use the first Accept
}
// body params
_sling = _sling.BodyJSON(project)
req, err := _sling.Request()
req.SetBasicAuth(prjUsr.Name, prjUsr.Passwd)
client := &http.Client{}
httpResponse, err := client.Do(req)
defer httpResponse.Body.Close()
return httpResponse.StatusCode, err
}
示例14: SearchGet
//Search for projects and repositories
//Implementation Notes
//The Search endpoint returns information about the projects and repositories
//offered at public status or related to the current logged in user.
//The response includes the project and repository list in a proper display order.
//@param q Search parameter for project and repository name.
//@return []Search
func (a testapi) SearchGet(q string, authInfo ...usrInfo) (int, apilib.Search, error) {
var httpCode int
var body []byte
var err error
_sling := sling.New().Get(a.basePath)
// create path and map variables
path := "/api/search"
_sling = _sling.Path(path)
type QueryParams struct {
Query string `url:"q,omitempty"`
}
_sling = _sling.QueryStruct(&QueryParams{Query: q})
if len(authInfo) > 0 {
httpCode, body, err = request(_sling, jsonAcceptHeader, authInfo[0])
} else {
httpCode, body, err = request(_sling, jsonAcceptHeader)
}
var successPayload = new(apilib.Search)
err = json.Unmarshal(body, &successPayload)
return httpCode, *successPayload, err
}
示例15: generateAuthToken
func (h *Hoverfly) generateAuthToken() (string, error) {
credentials := HoverflyAuthSchema{
Username: h.Username,
Password: h.Password,
}
jsonCredentials, err := json.Marshal(credentials)
if err != nil {
return "", err
}
request, err := sling.New().Post(h.buildURL("/api/token-auth")).Body(strings.NewReader(string(jsonCredentials))).Request()
if err != nil {
return "", err
}
response, err := h.httpClient.Do(request)
if err != nil {
return "", err
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", err
}
var authToken HoverflyAuthTokenSchema
err = json.Unmarshal(body, &authToken)
if err != nil {
return "", err
}
return authToken.Token, nil
}