Skip to content

Instantly share code, notes, and snippets.

@iraniamir
Created May 8, 2019 07:42
Show Gist options
  • Save iraniamir/d9218f0574293b9bc7564c532c24b459 to your computer and use it in GitHub Desktop.
Save iraniamir/d9218f0574293b9bc7564c532c24b459 to your computer and use it in GitHub Desktop.
IPv4 to Mongo ObjectID
package main
import (
"encoding/hex"
"fmt"
"strings"
"gopkg.in/mgo.v2/bson"
)
func main() {
fmt.Print(IPv4ToObjectID("127.0.0.1"))
fmt.Print(IPv4ToObjectID("255.255.255.255"))
}
func IPv4ToObjectID(IP string) bson.ObjectId {
ip := strings.Replace(IP, ".", "", -1)
ipLen := len(ip)
if ipLen < 12 {
ip = ip + strings.Repeat("0", 12-ipLen)
} else if len(ip) > 12 {
ip = ip[:12]
}
encodedIP := hex.EncodeToString([]byte(ip))
return bson.ObjectIdHex(encodedIP)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment