選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

main.go 780B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "strings"
  6. "encoding/json"
  7. )
  8. type jsonOutput struct {
  9. Ip string `json:"ip"`
  10. }
  11. func ipJsonOutput (w http.ResponseWriter, r *http.Request) {
  12. var ip jsonOutput
  13. ip.Ip = remoteAddr(r)
  14. output, err := json.Marshal(ip)
  15. if err != nil {
  16. w.Write([]byte(err.Error()))
  17. }
  18. w.Write([]byte(output))
  19. }
  20. func ipOutput (w http.ResponseWriter, r *http.Request) {
  21. ip := remoteAddr(r)
  22. w.Write([]byte(ip))
  23. }
  24. func remoteAddr ( r *http.Request) string {
  25. var ip string
  26. if r.RemoteAddr[0] == '[' {
  27. ip = strings.Split(r.RemoteAddr,"]")[0][1:]
  28. } else {
  29. ip = strings.Split(r.RemoteAddr,":")[0]
  30. }
  31. return ip
  32. }
  33. func main() {
  34. http.HandleFunc("/",ipOutput)
  35. http.HandleFunc("/json",ipJsonOutput)
  36. log.Fatal(http.ListenAndServe(":8080", nil))
  37. }