Пример #1
0
Файл: http.go Проект: abh/bgpapi
func ApiHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")

	vars := mux.Vars(r)

	neighbors_lock.RLock()
	defer neighbors_lock.RUnlock()

	type ipasnResult struct {
		ASN    ASN
		ASPath ASPath `json:",omitempty"`
		Name   string `json:",omitempty"`
		Prefix string `json:",omitempty"`
	}

	switch vars["method"] {
	case "ipasn":
		_ = r.ParseForm()
		ip := net.ParseIP(r.Form.Get("ip"))

		if ip == nil {
			w.WriteHeader(400)
			fmt.Fprintln(w, "Bad IP address")
			return
		}

		result := make(map[string]*ipasnResult)

		for neighbor, data := range neighbors {
			data.lock.RLock()
			defer data.lock.RUnlock()

			node := data.FindNode(&ip)
			if node.Bits() > 0 {
				result[neighbor] = new(ipasnResult)
				route := node.Value.(*Route)
				r := result[neighbor]
				r.ASN = ASN(route.PrimaryASN)
				r.ASPath = route.ASPath
				r.Name = ""
				r.Prefix = nodeToIPNet(node).String()
			}
		}

		json, err := json.Marshal(map[string]interface{}{"result": result})
		if err != nil {
			w.WriteHeader(500)
			log.Println("Error generating json", err)
			fmt.Fprintln(w, "Could not generate JSON")
		}

		fmt.Fprint(w, string(json), "\n")

	default:
		w.WriteHeader(404)
		return
	}

}