Browse Source

Added the "addr" parameter

Added the "addr" parameter in order to choose where to bind
fixed format with go fmt
tags/v1.0
Ramiro de Zavalia 5 years ago
parent
commit
0bc77b2600
1 changed files with 15 additions and 12 deletions
  1. 15
    12
      main.go

+ 15
- 12
main.go View File

package main package main


import ( import (
"log"
"net/http"
"strings"
"encoding/json"
"encoding/json"
"flag"
"log"
"net/http"
"strings"
) )


type jsonOutput struct { type jsonOutput struct {
Ip string `json:"ip"` Ip string `json:"ip"`
} }


func ipJsonOutput (w http.ResponseWriter, r *http.Request) {
func ipJsonOutput(w http.ResponseWriter, r *http.Request) {
var ip jsonOutput var ip jsonOutput
ip.Ip = remoteAddr(r) ip.Ip = remoteAddr(r)
output, err := json.Marshal(ip) output, err := json.Marshal(ip)
w.Write([]byte(output)) w.Write([]byte(output))
} }


func ipOutput (w http.ResponseWriter, r *http.Request) {
func ipOutput(w http.ResponseWriter, r *http.Request) {
ip := remoteAddr(r) ip := remoteAddr(r)
w.Write([]byte(ip)) w.Write([]byte(ip))
} }


func remoteAddr ( r *http.Request) string {
func remoteAddr(r *http.Request) string {
var ip string var ip string
if r.RemoteAddr[0] == '[' { if r.RemoteAddr[0] == '[' {
ip = strings.Split(r.RemoteAddr,"]")[0][1:]
ip = strings.Split(r.RemoteAddr, "]")[0][1:]
} else { } else {
ip = strings.Split(r.RemoteAddr,":")[0]
ip = strings.Split(r.RemoteAddr, ":")[0]
} }
return ip return ip
} }


func main() { func main() {
http.HandleFunc("/",ipOutput)
http.HandleFunc("/json",ipJsonOutput)
log.Fatal(http.ListenAndServe(":8080", nil))
addr := flag.String("addr", ":8080", "local ip:port to bind")
flag.Parse()
http.HandleFunc("/", ipOutput)
http.HandleFunc("/json", ipJsonOutput)
log.Fatal(http.ListenAndServe(*addr, nil))
} }

Loading…
Cancel
Save