本文整理汇总了Golang中github.com/dghubble/sling.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:28,代码来源:template.go
示例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
}
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:53,代码来源:hoverfly.go
示例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
}
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:33,代码来源:hoverfly.go
示例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
}
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:35,代码来源:hoverfly.go
示例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
}
开发者ID:DerPate,项目名称:swagger-codegen,代码行数:61,代码来源:PetApi.go
示例6: newClient
func newClient(httpClient *http.Client) *client {
base := sling.New().Client(httpClient).Base(facebookAPI)
return &client{
c: httpClient,
sling: base,
}
}
开发者ID:gooops,项目名称:gologin,代码行数:7,代码来源:verify.go
示例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
}
开发者ID:QualityUnit,项目名称:swagger-codegen,代码行数:65,代码来源:store_api.go
示例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
}
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:31,代码来源:hoverfly.go
示例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
}
开发者ID:QualityUnit,项目名称:swagger-codegen,代码行数:67,代码来源:user_api.go
示例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
}
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:34,代码来源:spectolab.go
示例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
}
开发者ID:odayny,项目名称:greentiger,代码行数:7,代码来源:userGet.go
示例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
}
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:28,代码来源:spectolab.go
示例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
}
开发者ID:vmware,项目名称:harbor,代码行数:34,代码来源:harborapi.go
示例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
}
开发者ID:vmware,项目名称:harbor,代码行数:34,代码来源:harborapi_test.go
示例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
}
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:34,代码来源:hoverfly.go
示例16: FindPetsByStatus
//func (a PetApi) FindPetsByStatus (Status []string) ([]Pet, error) {
func (a PetApi) FindPetsByStatus(Status []string) ([]Pet, error) {
_sling := sling.New().Get(a.basePath)
// create path and map variables
path := "/v2/pet/findByStatus"
_sling = _sling.Path(path)
type QueryParams struct {
Status []string `url:"status,omitempty"`
}
_sling = _sling.QueryStruct(&QueryParams{Status: Status})
// accept header
accepts := []string{"application/json", "application/xml"}
for key := range accepts {
_sling = _sling.Set("Accept", accepts[key])
break // only use the first Accept
}
response := new([]Pet)
_, err := _sling.ReceiveSuccess(response)
//fmt.Println("FindPetsByStatus response: ", response, resp, err)
return *response, err
}
开发者ID:achew22,项目名称:swagger-codegen,代码行数:26,代码来源:PetApi.go
示例17: LoginUser
//func (a UserApi) LoginUser (Username string, Password string) (string, error) {
func (a UserApi) LoginUser(Username string, Password string) (string, error) {
_sling := sling.New().Get(a.basePath)
// create path and map variables
path := "/v2/user/login"
_sling = _sling.Path(path)
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/json", "application/xml"}
for key := range accepts {
_sling = _sling.Set("Accept", accepts[key])
break // only use the first Accept
}
response := new(string)
_, err := _sling.ReceiveSuccess(response)
//fmt.Println("LoginUser response: ", response, resp, err)
return *response, err
}
开发者ID:achew22,项目名称:swagger-codegen,代码行数:27,代码来源:UserApi.go
示例18: UpdatePetWithForm
//func (a PetApi) UpdatePetWithForm (PetId string, Name string, Status string) (error) {
func (a PetApi) UpdatePetWithForm(PetId string, Name string, Status string) error {
_sling := sling.New().Post(a.basePath)
// create path and map variables
path := "/v2/pet/{petId}"
path = strings.Replace(path, "{"+"petId"+"}", fmt.Sprintf("%v", PetId), -1)
_sling = _sling.Path(path)
// accept header
accepts := []string{"application/json", "application/xml"}
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})
_, err := _sling.ReceiveSuccess(nil)
//fmt.Println("UpdatePetWithForm response: void, ", resp, err)
return err
}
开发者ID:achew22,项目名称:swagger-codegen,代码行数:28,代码来源:PetApi.go
示例19: UploadFile
//func (a PetApi) UploadFile (PetId int64, AdditionalMetadata string, File *os.File) (error) {
func (a PetApi) UploadFile(PetId int64, AdditionalMetadata string, File *os.File) error {
_sling := sling.New().Post(a.basePath)
// create path and map variables
path := "/v2/pet/{petId}/uploadImage"
path = strings.Replace(path, "{"+"petId"+"}", fmt.Sprintf("%v", PetId), -1)
_sling = _sling.Path(path)
// accept header
accepts := []string{"application/json", "application/xml"}
for key := range accepts {
_sling = _sling.Set("Accept", accepts[key])
break // only use the first Accept
}
type FormParams struct {
AdditionalMetadata string `url:"additionalMetadata,omitempty"`
File *os.File `url:"file,omitempty"`
}
_sling = _sling.BodyForm(&FormParams{AdditionalMetadata: AdditionalMetadata, File: File})
_, err := _sling.ReceiveSuccess(nil)
//fmt.Println("UploadFile response: void, ", resp, err)
return err
}
开发者ID:achew22,项目名称:swagger-codegen,代码行数:28,代码来源:PetApi.go
示例20: DeleteSimulations
// Wipe will call the records endpoint in Hoverfly with a DELETE request, triggering Hoverfly to wipe the database
func (h *Hoverfly) DeleteSimulations() error {
url := h.buildURL("/api/records")
slingRequest := sling.New().Delete(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")
}
defer response.Body.Close()
if response.StatusCode == 401 {
return errors.New("Hoverfly requires authentication")
}
if response.StatusCode != 200 {
return errors.New("Simulations were not deleted from Hoverfly")
}
return nil
}
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:36,代码来源:hoverfly.go
注:本文中的github.com/dghubble/sling.New函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论