bmconsole.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package bmconsole
  15. import (
  16. "bytes"
  17. "context"
  18. "fmt"
  19. "net/http"
  20. "strings"
  21. "yunion.io/x/pkg/errors"
  22. "yunion.io/x/pkg/util/httputils"
  23. )
  24. type SBMCConsole struct {
  25. client *http.Client
  26. username string
  27. password string
  28. host string
  29. isDebug bool
  30. }
  31. func NewBMCConsole(host, username, password string, isDebug bool) *SBMCConsole {
  32. client := httputils.GetDefaultClient()
  33. return &SBMCConsole{
  34. client: client,
  35. host: host,
  36. username: username,
  37. password: password,
  38. isDebug: isDebug,
  39. }
  40. }
  41. func setCookieHeader(hdr http.Header, cookies map[string]string) {
  42. cookieParts := make([]string, 0)
  43. for k, v := range cookies {
  44. cookieParts = append(cookieParts, k+"="+v)
  45. }
  46. if len(cookieParts) > 0 {
  47. hdr.Set("Cookie", strings.Join(cookieParts, "; "))
  48. }
  49. }
  50. func (r *SBMCConsole) RawRequest(ctx context.Context, method httputils.THttpMethod, path string, header http.Header, body []byte) (http.Header, []byte, error) {
  51. urlStr := httputils.JoinPath(fmt.Sprintf("https://%s", r.host), path)
  52. if header == nil {
  53. header = http.Header{}
  54. }
  55. header.Set("Connection", "Close")
  56. header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:69.0) Gecko/20100101 Firefox/69.0")
  57. resp, err := httputils.Request(r.client, ctx, method, urlStr, header, bytes.NewReader(body), r.isDebug)
  58. var bodyStr string
  59. if body != nil {
  60. bodyStr = string(body)
  61. }
  62. hdr, rspBody, err := httputils.ParseResponse(bodyStr, resp, err, r.isDebug)
  63. if err != nil {
  64. return nil, nil, errors.Wrap(err, "httputils.Request")
  65. }
  66. return hdr, rspBody, nil
  67. }