Guest User

Untitled

a guest
Feb 15th, 2017
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.33 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "encoding/json"
  5.     "log"
  6.     "net/http"
  7.     "net/url"
  8.     "strings"
  9. )
  10.  
  11. type Server struct {
  12.     Endpoint string
  13.     User     string
  14.     Password string
  15. }
  16.  
  17. type Ip struct {
  18.     Tenant string `json:"tenant"`
  19.     Subnet string `json:"subnet"`
  20. }
  21.  
  22. type Net struct {
  23.     Tenant string `json:"tenant"`
  24.     Subnet string `json:"subent"`
  25.     Ip2    string `json:"ip"`
  26. }
  27.  
  28. type Error struct {
  29.     Message string `json:"message"`
  30. }
  31.  
  32. type Data struct {
  33.     Net   Net   `json:"data"`
  34.     Error Error `json:"error"`
  35. }
  36.  
  37. func (c *Server) GetIp(ip *Ip) string {
  38.     data1 := url.Values{}
  39.     data1.Add("tenant", ip.Tenant)
  40.     data1.Add("subnet", ip.Subnet)
  41.     req, err := http.NewRequest("POST", c.Endpoint, strings.NewReader(data1.Encode()))
  42.     req.SetBasicAuth(c.User, c.Password)
  43.     req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  44.     cli := &http.Client{}
  45.     resp, err := cli.Do(req)
  46.     if err != nil {
  47.         log.Fatalln(err)
  48.     }
  49.     defer resp.Body.Close()
  50.     decoder := json.NewDecoder(resp.Body)
  51.     data := Data{}
  52.     err = decoder.Decode(&data)
  53.     if err != nil {
  54.         log.Fatalln(err)
  55.     }
  56.     return data.Net.Ip2
  57. }
  58.  
  59. func main() {
  60.     client := Server{
  61.         Endpoint: "http://192.168.122.162:7000/getip",
  62.         User:     "testk",
  63.         Password: "testk",
  64.     }
  65.     ip := Ip{
  66.         Tenant: "testk",
  67.         Subnet: "dev",
  68.     }
  69.     data := client.GetIp(&ip)
  70.     log.Println(data)
  71. }
Add Comment
Please, Sign In to add comment