go mod init github.com/yourusername/yourproject
go env GOPATH //This command is also useful for check the location.
go list -m all
import
https://blog.csdn.net/yeshang_lady/article/details/134272955
https://home.gamer.com.tw/artwork.php?sn=5463024
In smf, take sm_context.go in package context as example, below are the functions it import, some are the functions from the official go language, the other imported lines including "github.com/…" are from the github of free5gc.
You can see the reference about how you can add the frepository into your code, in free5gc's NFs, every NF has a file called go.mod, recording the url it imports.
Until here, Im curious about if the free5gc works without internet, because the modules from github are imported, not copied to local host, so I do a test closing the network interface and running the 5gc.
The result is that it needs addresses binded for using http service, but it doesnt explan whether the github module affect the program.
echo $GOPATH
export GOPATH=/home/ubuntu/free5gc_AUSF_v2.0
package main
import (
"fmt"
"strings"
)
func main() {
suci := "suci-0-208-93-0000-0-0-0000000003"
parts := strings.Split(suci, "-")
lastPart := parts[len(parts)-1]
supi := "imsi-20893" + lastPart
fmt.Println(supi) // 輸出: imsi-208930000000003
}
go mod init example.com/myapp
go run main.go
go : 無法辨識 'go' 詞彙是否為 Cmdlet、函數、指令檔或可執行程式的名稱。請檢查名稱拼字是否正確,如果包含路徑的話,請確認路徑是否正
確,然後再試一次。
位於 線路:1 字元:1
+ go run main.go
+ ~~
+ CategoryInfo : ObjectNotFound: (go:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
go version
// suci-0(SUPI type: IMSI)-mcc-mnc-routingIndicator-protectionScheme-homeNetworkPublicKeyID-schemeOutput.
// TODO:
// suci-1(SUPI type: NAI)-homeNetworkID-routingIndicator-protectionScheme-homeNetworkPublicKeyID-schemeOutput.
const (
PrefixPlace = iota
SupiTypePlace
MccPlace
MncPlace
RoutingIndicatorPlace
SchemePlace
HNPublicKeyIDPlace
SchemeOuputPlace
MaxPlace
)
const (
PrefixIMSI = "imsi-"
PrefixSUCI = "suci"
SupiTypeIMSI = "0"
NullScheme = "0"
ProfileAScheme = "1"
ProfileBScheme = "2"
)
func ToSupi(suci string, suciProfiles []SuciProfile) (string, error) {
suciPart := strings.Split(suci, "-")
logger.SuciLog.Infof("suciPart: %+v", suciPart)
suciPrefix := suciPart[0]
if suciPrefix == "imsi" || suciPrefix == "nai" {
logger.SuciLog.Infof("Got supi\n")
return suci, nil
} else if suciPrefix == PrefixSUCI {
if len(suciPart) < 6 {
return "", fmt.Errorf("Suci with wrong format\n")
}
} else {
return "", fmt.Errorf("Unknown suciPrefix [%s]", suciPrefix)
}
logger.SuciLog.Infof("scheme %s\n", suciPart[SchemePlace])
scheme := suciPart[SchemePlace]
mccMnc := suciPart[MccPlace] + suciPart[MncPlace]
supiPrefix := PrefixIMSI
if suciPrefix == PrefixSUCI && suciPart[SupiTypePlace] == SupiTypeIMSI {
logger.SuciLog.Infof("SUPI type is IMSI\n")
}
if scheme == NullScheme { // NULL scheme
return supiPrefix + mccMnc + suciPart[len(suciPart)-1], nil
}
.
.
.
package main
import "fmt"
func main() {
snName := "Hello, Go!"
P0 := []byte(snName)
fmt.Println("Original string:", snName)
fmt.Println("Byte slice:", P0)
}
package main
import "fmt"
func getEmptyString() string {
return ""
}
func main() {
result := getEmptyString()
fmt.Println(result) // 輸出一個空行,因為 result 是一個空字符串
}
package main
import "fmt"
// 返回空字符串
func getEmptyString() string {
return ""
}
// 返回空指針
func getNilPointer() *int {
return nil
}
// 返回空切片
func getNilSlice() []int {
return nil
}
// 返回空映射
func getNilMap() map[string]int {
return nil
}
// 返回空通道
func getNilChannel() chan int {
return nil
}
// 返回空接口
func getNilInterface() interface{} {
return nil
}
func main() {
fmt.Println("Empty String:", getEmptyString())
fmt.Println("Nil Pointer:", getNilPointer())
fmt.Println("Nil Slice:", getNilSlice())
fmt.Println("Nil Map:", getNilMap())
fmt.Println("Nil Channel:", getNilChannel())
fmt.Println("Nil Interface:", getNilInterface())
}
package models
type LinksValueSchema struct {
Href string `json:"href"`
}
linksValue := models.LinksValueSchema{Href: putLink}
responseBody.Links = make(map[string]models.LinksValueSchema)
responseBody.Links["5g-aka"] = linksValue
//You can use this example to print the result, and see the structure.
package main
import (
"fmt"
"models"
)
func main() {
// 假設 putLink 是一個有效的 URL 字串
putLink := "https://example.com/5g-aka"
// 創建 LinksValueSchema 實例
linksValue := models.LinksValueSchema{Href: putLink}
// 初始化 responseBody 的 Links 映射
var responseBody models.ResponseBody
responseBody.Links = make(map[string]models.LinksValueSchema)
// 將 linksValue 添加到映射中,鍵為 "5g-aka"
responseBody.Links["5g-aka"] = linksValue
// 打印結果
fmt.Println(responseBody)
}
func strictHex(s string, n int) string {
l := len(s)
if l < n {
return fmt.Sprintf(strings.Repeat("0", n-l) + s)
} else {
return s[l-n : l]
}
}
package main
import (
"fmt"
"strings"
)
func strictHex(s string, n int) string {
l := len(s)
if l < n {
return fmt.Sprintf(strings.Repeat("0", n-l) + s)
} else {
return s[l-n : l]
}
}
func main() {
authSubsSequenceNumber := "12345"
sqnStr := strictHex(authSubsSequenceNumber, 12)
fmt.Println(sqnStr) // 輸出 "0000000012345"
authSubsSequenceNumber = "1234567890ABCDEF"
sqnStr = strictHex(authSubsSequenceNumber, 12)
fmt.Println(sqnStr) // 輸出 "7890ABCDEF"
}
package main
import (
"fmt"
"math/big"
)
func main() {
sqnStr := "123ABC"
bigSQN := new(big.Int)
bigSQN, success := bigSQN.SetString(sqnStr, 16)
if !success {
fmt.Println("轉換失敗")
} else {
fmt.Println("轉換成功:", bigSQN)
}
}
// 假設 authSubs.SequenceNumber 是一個十六進制字符串
sqnStr := "16f3b3f70ff2"
bigSQN := new(big.Int)
bigSQN, success := bigSQN.SetString(sqnStr, 16)
if !success {
logger.GmmLog.Infof("轉換失敗")
return nil, fmt.Errorf("無法轉換序列號")
}
// 進行大數運算,例如增加序列號
bigInc := big.NewInt(1)
bigSQN.Add(bigSQN, bigInc)
// 將結果轉換回十六進制字符串
newSqnStr := fmt.Sprintf("%x", bigSQN)
logger.GmmLog.Infof("新的序列號: %s", newSqnStr)
package main
import (
"fmt"
"math/big"
)
func main() {
// 定義常數和初始值
SqnMAx := int64(0xFFFFFFFFFFFF)
sqnStr := "16f3b3f70ff2"
// 將 sqnStr 轉換為大數
bigSQN := new(big.Int)
bigSQN, success := bigSQN.SetString(sqnStr, 16)
if !success {
fmt.Println("轉換失敗")
return
}
// 定義增量和最大值
bigInc := big.NewInt(1)
bigP := big.NewInt(SqnMAx)
// 增加序列號並進行模運算
bigSQN.Add(bigSQN, bigInc)
bigSQN.Mod(bigSQN, bigP)
// 將結果轉換回十六進制字符串
newSqnStr := fmt.Sprintf("%x", bigSQN)
fmt.Println("新的序列號:", newSqnStr)
}
package main
import "fmt"
// 全域變數宣告
var globalVar int = 100
func main() {
// 宣告並初始化變數
var a int = 10
var b = 20 // 類型推斷
var c int // 宣告但不初始化,默認值為 0
fmt.Println(a, b, c)
fmt.Println(globalVar)
}
package main
import "fmt"
func main() {
var (
a int = 10
b string = "hello"
c float64 = 3.14
)
fmt.Println(a, b, c)
}
package main
import "fmt"
func main() {
const pi = 3.14159
const hello = "Hello, World!"
fmt.Println(pi)
fmt.Println(hello)
}
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
result := add(3, 4)
fmt.Println(result) // 輸出: 7
}
package main
import "fmt"
func swap(a, b int) (int, int) {
return b, a
}
func main() {
x, y := swap(3, 4)
fmt.Println(x, y) // 輸出: 4 3
}
package main
import "fmt"
func divide(a, b int) (result int, err error) {
if b == 0 {
err = fmt.Errorf("division by zero")
return
}
result = a / b
return
}
func main() {
result, err := divide(10, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result) // 輸出: Result: 5
}
}
package main
import "fmt"
func main() {
// 使用 := 進行變數宣告和賦值
a := 5 // a 是 int 型別,值為 5
b := "hello" // b 是 string 型別,值為 "hello"
c := 3.14 // c 是 float64 型別,值為 3.14
// 打印變數的值
fmt.Println(a) // 輸出: 5
fmt.Println(b) // 輸出: hello
fmt.Println(c) // 輸出: 3.14
}
package main
import "fmt"
func main() {
// 使用 := 宣告並初始化變數
x := 10
fmt.Println(x) // 輸出: 10
// 使用 = 賦值給已宣告的變數
x = 20
fmt.Println(x) // 輸出: 20
}
package main
import "fmt"
func main() {
a := 5
b := 5
c := 10
// 使用 == 比較變數的值
fmt.Println(a == b) // 輸出: true
fmt.Println(a == c) // 輸出: false
}
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
mightPanic()
fmt.Println("This will not be printed if panic is not recovered")
}
func mightPanic() {
panic("Something went wrong!")
}
package main
import (
"fmt"
)
func main() {
safeFunction()
fmt.Println("Program continues to run...")
}
func safeFunction() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in safeFunction:", r)
}
}()
panicFunction()
}
func panicFunction() {
panic("A severe error occurred!")
}
package main
import (
"fmt"
)
func main() {
// 定義一個 map[string]interface{}
data := make(map[string]interface{})
// 向 map 中添加不同類型的數據
data["name"] = "Alice"
data["age"] = 30
data["isStudent"] = false
data["grades"] = []int{85, 90, 92}
// 訪問 map 中的數據
fmt.Println("Name:", data["name"])
fmt.Println("Age:", data["age"])
fmt.Println("Is Student:", data["isStudent"])
fmt.Println("Grades:", data["grades"])
}
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonString := `{
"name": "Bob",
"age": 25,
"isStudent": true,
"grades": [88, 76, 93]
}`
var data map[string]interface{}
// 將 JSON 字符串解析為 map[string]interface{}
err := json.Unmarshal([]byte(jsonString), &data)
if err != nil {
fmt.Println("Error:", err)
return
}
// 訪問解析後的數據
fmt.Println("Name:", data["name"])
fmt.Println("Age:", data["age"])
fmt.Println("Is Student:", data["isStudent"])
fmt.Println("Grades:", data["grades"])
}
func main() {
data := map[string]interface{}{
"name": "Alice",
"age": 30,
"isStudent": false,
"grades": []int{85, 90, 92},
}
// 類型斷言
name, ok := data["name"].(string)
if !ok {
fmt.Println("Name is not a string")
} else {
fmt.Println("Name:", name)
}
age, ok := data["age"].(int)
if !ok {
fmt.Println("Age is not an int")
} else {
fmt.Println("Age:", age)
}
isStudent, ok := data["isStudent"].(bool)
if !ok {
fmt.Println("isStudent is not a bool")
} else {
fmt.Println("Is Student:", isStudent)
}
grades, ok := data["grades"].([]int)
if !ok {
fmt.Println("Grades is not a []int")
} else {
fmt.Println("Grades:", grades)
}
}
go get go.mongodb.org/mongo-driver/mongo
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
"log"
"time"
)
func main() {
// 設置 MongoDB 連接選項
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// 連接到 MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// 檢查連接是否成功
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
// 指定數據庫和集合
collection := client.Database("testdb").Collection("testcollection")
// 查詢一個文檔
var result bson.M
filter := bson.M{"name": "Alice"}
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
// 打印結果
fmt.Println("Result:", result)
// 關閉連接
err = client.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")
}
// 假設 result 已經包含從 MongoDB 查詢到的數據
name, ok := result["name"].(string)
if ok {
fmt.Println("Name:", name)
}
age, ok := result["age"].(int32)
if ok {
fmt.Println("Age:", age)
}
authSubs := map[string]interface{}{
"authenticationMethod": "5G_AKA",
"permanentKey": map[string]interface{}{
"permanentKeyValue": "8baf473f2f8fd09487cccbd7097c6862",
"encryptionAlgorithm": "0",
"encryptionKey": "0",
},
"sequenceNumber": "000000000034",
"authenticationManagementField": "8000",
"milenage": map[string]interface{}{
"op": map[string]interface{}{
"opValue": "8e27b6af0e692e750f32667a3b14605d",
"encryptionAlgorithm": "0",
"encryptionKey": "0",
},
"opc": map[string]interface{}{
"opcValue": "",
"encryptionAlgorithm": "0",
"encryptionKey": "0",
},
},
"ueId": "imsi-208930000000003",
}
// 先從 map 中取出 permanentKey
permanentKey, ok := authSubs["permanentKey"].(map[string]interface{})
if !ok {
// 處理錯誤,例如 permanentKey 字段不存在或類型不匹配
log.Fatalf("permanentKey not found or not a map[string]interface{}")
}
// 從 permanentKey 中取出 permanentKeyValue
permanentKeyValue, ok := permanentKey["permanentKeyValue"].(string)
if !ok {
// 處理錯誤,例如 permanentKeyValue 字段不存在或類型不匹配
log.Fatalf("permanentKeyValue not found or not a string")
}
fmt.Println("PermanentKeyValue:", permanentKeyValue)
type PermanentKey struct {
PermanentKeyValue string `json:"permanentKeyValue"`
EncryptionAlgorithm string `json:"encryptionAlgorithm"`
EncryptionKey string `json:"encryptionKey"`
}
type Milenage struct {
Op struct {
OpValue string `json:"opValue"`
EncryptionAlgorithm string `json:"encryptionAlgorithm"`
EncryptionKey string `json:"encryptionKey"`
} `json:"op"`
Opc struct {
OpcValue string `json:"opcValue"`
EncryptionAlgorithm string `json:"encryptionAlgorithm"`
EncryptionKey string `json:"encryptionKey"`
} `json:"opc"`
}
type AuthSubs struct {
AuthenticationMethod string `json:"authenticationMethod"`
PermanentKey *PermanentKey `json:"permanentKey"`
SequenceNumber string `json:"sequenceNumber"`
AuthenticationManagementField string `json:"authenticationManagementField"`
Milenage *Milenage `json:"milenage"`
UeId string `json:"ueId"`
}
func main() {
var authSubs AuthSubs
// 假設從數據庫中獲取數據並反序列化為 authSubs 結構體
// ...
// 直接訪問 PermanentKeyValue 字段
fmt.Println("PermanentKeyValue:", authSubs.PermanentKey.PermanentKeyValue)
}
package main
import (
"fmt"
)
type ProblemDetails struct {
Status int32
Detail string // 假設有其他欄位
}
func main() {
// 假設 rsp 是一個 HTTP 回應物件,StatusCode 是其狀態碼
rsp := struct {
StatusCode int
}{
StatusCode: 404, // 假設狀態碼為 404
}
var problemDetails ProblemDetails
// 將 rsp.StatusCode 轉換為 int32,並賦值給 problemDetails.Status
problemDetails.Status = int32(rsp.StatusCode)
fmt.Printf("ProblemDetails 的狀態碼為: %d\n", problemDetails.Status)
}
package main
import (
"fmt"
)
func main() {
num := 255
fmt.Printf("%x\n", num) // 輸出:ff
}
package main
import (
"fmt"
)
func main() {
str := "hello"
fmt.Printf("%x\n", str) // 輸出:68656c6c6f
}
package main
import (
"fmt"
)
func main() {
data := []byte{0, 1, 2, 10, 15, 255}
fmt.Printf("%x\n", data) // 輸出:0001020a0fff
}
package main
import (
"fmt"
)
func main() {
data := []byte{0, 1, 2, 10, 15, 255}
fmt.Printf("% x\n", data) // 輸出:00 01 02 0a 0f ff
}
package main
import (
"fmt"
)
func main() {
num := 255
str := "hello"
data := []byte{0, 1, 2, 10, 15, 255}
fmt.Printf("Number in hex: %x\n", num) // Number in hex: ff
fmt.Printf("String in hex: %x\n", str) // String in hex: 68656c6c6f
fmt.Printf("Bytes in hex: %x\n", data) // Bytes in hex: 0001020a0fff
fmt.Printf("Bytes with space: % x\n", data) // Bytes with space: 00 01 02 0a 0f ff
}
package main
import (
"fmt"
)
type Person struct {
Name string
Age int
Email string
}
func main() {
p := Person{
Name: "Alice",
Age: 30,
Email: "alice@example.com",
}
// 使用%v打印 struct
fmt.Printf("%v\n", p) // {Alice 30 alice@example.com}
// 使用%+v打印 struct,包括字段名
fmt.Printf("%+v\n", p) // {Name:Alice Age:30 Email:alice@example.com}
// 使用%#v打印 struct,顯示詳細信息
fmt.Printf("%#v\n", p) // main.Person{Name:"Alice", Age:30, Email:"alice@example.com"}
// 使用%T打印 struct 的類型
fmt.Printf("%T\n", p) // main.Person
// 打印 struct 的字段值,分別用不同格式
fmt.Printf("Name: %s, Age: %d (bin: %b, hex: %x), Email: %s\n", p.Name, p.Age, p.Age, p.Age, p.Email)
}
{Alice 30 alice@example.com}
{Name:Alice Age:30 Email:alice@example.com}
main.Person{Name:"Alice", Age:30, Email:"alice@example.com"}
main.Person
Name: Alice, Age: 30 (bin: 11110, hex: 1e), Email: alice@example.com
Authentication Server Services / ETSI TS 129 509 V16.7.0 (2021-04)
Security architecture and procedures for 5G System / ETSI TS 133 501 V15.2.0 (2018-10)
NGAP