navigator/api/beacon/v1/api.go

52 lines
1.5 KiB
Go
Raw Normal View History

package v1
import (
"encoding/json"
2020-02-02 16:39:15 +08:00
"fmt"
"git.eve.moe/jackyyf/navigator/api/beacon"
"git.eve.moe/jackyyf/navigator/mapping"
2020-02-01 15:06:00 +08:00
"git.eve.moe/jackyyf/navigator/mapping/firefly"
"git.eve.moe/jackyyf/navigator/utils"
"net/http"
)
var (
serveMux = http.NewServeMux()
)
func init() {
serveMux.HandleFunc("/getNodes", func(resp http.ResponseWriter, req *http.Request) {
host := utils.GetRemoteIP(req)
nodes := mapping.GetNodes()
if nodes == nil {
utils.ResponseWithJsonError(resp, http.StatusInternalServerError, "Unable to get nodes")
return
}
suffix := mapping.GetSuffix(host)
resp.Header().Set("Content-Type", "application/json")
resp.WriteHeader(http.StatusOK)
2020-02-01 15:06:00 +08:00
json.NewEncoder(resp).Encode(map[string]interface{}{
"nodes": nodes,
"suffix": suffix,
})
})
2020-02-01 15:06:00 +08:00
serveMux.HandleFunc("/submit", func(resp http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
utils.ResponseWithJsonError(resp, http.StatusMethodNotAllowed, "Method is not accepted with this method.")
return
}
request := make(map[string]float64)
decoder := json.NewDecoder(req.Body)
if err := decoder.Decode(&request); err != nil {
utils.ResponseWithJsonError(resp, http.StatusBadRequest, "Malformed JSON payload.")
return
}
remoteIp := utils.GetRemoteIP(req)
go firefly.AddSpeedTestResult(remoteIp, request)
2020-02-02 16:39:15 +08:00
resp.Header().Set("Content-Type", "application/json")
2020-02-01 15:06:00 +08:00
resp.WriteHeader(http.StatusOK)
2020-02-02 16:39:15 +08:00
fmt.Fprint(resp, "true")
2020-02-01 15:06:00 +08:00
})
beacon.RegisterApi("v1", serveMux)
}