Skip to content

net: net.IPNet should implement encoding.TextMarshaler and TextUnmarshaler #12803

Closed
@gucki

Description

@gucki
package main

import (
  "encoding/json"
  "fmt"
  "net"
)

var input = `
{
  "network": "127.0.0.1/24"
}
`

type A struct {
  Network net.IPNet `json:"network"`
}

func main() {
  var val A

  if err := json.Unmarshal([]byte(input), &val); err != nil {
    panic(err)
  }

  fmt.Println(val)
}

Fails with "panic: json: cannot unmarshal string into Go value of type net.IPNet".

go version go1.5.1 linux/amd64

Activity

changed the title [-]enable JSON encoding/ decoding of net.NetIP[/-] [+]net: enable JSON encoding/decoding of net.NetIP[/+] on Oct 1, 2015
changed the title [-]net: enable JSON encoding/decoding of net.NetIP[/-] [+]net: net.IPNet should implement encoding.TextMarshaler and TextUnmarshaler[/+] on Oct 2, 2015
adg

adg commented on Oct 2, 2015

@adg
Contributor

net.IP implements encoding.TextUnmarshaler and encoding.TextMarshaler, so net.IPNet could too.

net.IPNet is a combination of net.IP and net.IPMask. The latter does not implement the encoding interfaces, so maybe IPMask should be changed also.

nerdatmath

nerdatmath commented on Oct 13, 2015

@nerdatmath
Contributor

What should a net.IPMask look like as a JSON string? I see a few options.

  • Match IPMask.String - always a hex representation of the mask
  • Match IPNet.String after the slash (a decimal integer or hex representation depending on whether the mask is a valid CIDR or not)
  • Match IPNet.String, including the slash and following characters (always start with a slash).

Then, independently of the above, should net.IPNet marshal/unmarshal a format matching IPNet.String (as @gucki requested), or just a JSON expansion of the IPNet struct, such as this:

{ "IP": "127.0.0.1", "Mask": "8" }
rsc

rsc commented on Oct 23, 2015

@rsc
Contributor

Too late, I'm afraid. That would change the current encodings.

http://play.golang.org/p/DY7Juqs9vT

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net"
)

func main() {
    js, err := json.Marshal(net.IPNet{})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(js))
}
gucki

gucki commented on Oct 24, 2015

@gucki
Author

@rsc Sorry, I don't get why parsing "127.0.0.1/24" into a net.IPNET could not be implemented anyway?

locked and limited conversation to collaborators on Oct 24, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @rsc@gucki@nerdatmath@adg@gopherbot

        Issue actions

          net: net.IPNet should implement encoding.TextMarshaler and TextUnmarshaler · Issue #12803 · golang/go