Why url.URL.User field not to be marshaled?

package main

import (
“encoding/json”
“fmt”
“net/url”
“log”
)

func main() {

// u is type *url.URL
u, err := url.Parse("http://username:password@bing.com/search?q=dotnet")
if err != nil {
	log.Fatal(err)
}

// u.User is type *url.Userinfo, it is parsed from "username:password"
fmt.Printf("%T, %v\n",u.User, *u.User)

// u.User is empty, we lost it
user,_ := json.Marshal(u)
fmt.Println(string(user))

}

as above code, I got result:

`
*url.Userinfo, {username password true}

{“Scheme”:“http”,“Opaque”:"",“User”:{},“Host”:“bing.com”,“Path”:"/search",“RawPath”:"",“RawQuery”:“q=dotnet”,“Fragment”:""}
`

as the topic title, why go not marshal User field? for security reason?

Hey @hilerchyn,

I believe the reason it’s not encoding the user values is simply because the url.UserInfo’s username and password fields are unexported so therefore won’t get marshalled since the encoders only encode exported fields.

type Userinfo struct {
    username    string
    password    string
    passwordSet bool
}

Edit: You can do something like this if you want to have the url.Userinfo encoded alongside the url.URL values. There’s probably a better way, but this is just off of the top of my head.

ALWAYS CHECK YOUR ERRORS :fire:

3 Likes

@radovskyb thank you

1 Like

@dfc I’ll keep it in mind

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.