-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
78 lines (70 loc) · 2.16 KB
/
server.go
File metadata and controls
78 lines (70 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"encoding/json"
"log"
"net/http"
)
// RunServer starts a simple HTTP API for subnet calculations.
// Endpoints:
//
// GET /api/subnet?cidr=<ip/prefix>
//
// Example:
//
// curl 'http://localhost:8080/api/subnet?cidr=192.168.1.10/26'
func RunServer(addr string) error {
mux := http.NewServeMux()
mux.HandleFunc("/api/subnet", func(w http.ResponseWriter, r *http.Request) {
// Basic CORS for local dev
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
cidr := r.URL.Query().Get("cidr")
if cidr == "" {
http.Error(w, "missing cidr query param", http.StatusBadRequest)
return
}
s := Subnet{ip: cidr}
address, prefix, total, networks, hosts, broadcasts, err := s.calc(cidr)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resp := map[string]interface{}{
"address": address,
"prefix": prefix,
"total": total,
"networks": networks,
"hosts": hosts,
"broadcasts": broadcasts,
}
// Add detailed fields while keeping existing keys for compatibility
if a, p, mask, wildcard, netAddr, first, last, bcast, usable, _, derr := computeDetails(cidr); derr == nil {
resp["prefix"] = p // keep prefix consistent
resp["subnetMask"] = mask
resp["wildcardMask"] = wildcard
resp["network"] = netAddr
resp["firstHost"] = first
resp["lastHost"] = last
resp["broadcast"] = bcast
resp["usableHosts"] = usable
_ = a // already included as address
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(resp); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
log.Printf("subnet API listening on %s\n", addr)
log.Printf("try: http://localhost%[1]s/api/subnet?cidr=192.168.1.10/26\n", addr)
return http.ListenAndServe(addr, mux)
}