diff options
Diffstat (limited to 'api')
| -rw-r--r-- | api/api.go | 1 | ||||
| -rw-r--r-- | api/ip.go | 38 | ||||
| -rw-r--r-- | api/routes.go | 23 |
3 files changed, 61 insertions, 1 deletions
@@ -30,6 +30,7 @@ func Serve(port int) { // Define Mux Router r := mux.NewRouter() r.HandleFunc("/health", healthCheckFunc) + r.HandleFunc("/", insertFunc).Methods("POST") http.Handle("/", r) diff --git a/api/ip.go b/api/ip.go new file mode 100644 index 0000000..d65117f --- /dev/null +++ b/api/ip.go @@ -0,0 +1,38 @@ +package api + +import ( + "fmt" + "net" + "net/http" + "strings" +) + +func getIP(r *http.Request) (string, error) { + //Get IP from the X-REAL-IP header + ip := r.Header.Get("X-REAL-IP") + netIP := net.ParseIP(ip) + if netIP != nil { + return ip, nil + } + + //Get IP from X-FORWARDED-FOR header + ips := r.Header.Get("X-FORWARDED-FOR") + splitIps := strings.Split(ips, ",") + for _, ip := range splitIps { + netIP := net.ParseIP(ip) + if netIP != nil { + return ip, nil + } + } + + //Get IP from RemoteAddr + ip, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return "", err + } + netIP = net.ParseIP(ip) + if netIP != nil { + return ip, nil + } + return "", fmt.Errorf("No valid ip found") +} diff --git a/api/routes.go b/api/routes.go index edb5a02..655d18b 100644 --- a/api/routes.go +++ b/api/routes.go @@ -3,8 +3,29 @@ package api import ( "fmt" "net/http" + + "github.com/jackyzha0/ctrl-v/db" + + log "github.com/sirupsen/logrus" ) func healthCheckFunc(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "status ok") + fmt.Fprint(w, "status ok") +} + +func insertFunc(w http.ResponseWriter, r *http.Request) { + // get content + _ = r.ParseMultipartForm(0) + content := r.FormValue("content") + + // get ip + ip, _ := getIP(r) + + log.Infof("got content `%s` and ip %s", content, ip) + + // insert content + err := db.New(ip, content) + if err != nil { + fmt.Fprintf(w, "got err: %s", err.Error()) + } } |