[go-nuts] How to design HTTP request between HTTP servers
Hi, I have been learning Golang for some few months now but still find it difficult to design some applications. I have two HTTP servers A and B and would like to do the following 1. server A send an HTTP PUT request with JSON body to server B. 2. If server B is not available, server A retry until server B is up and respond to the request 3. In server B response body is a timer value received by server A 4. Server B uses the timer value (eg 45) to send a PATCH request using the value as interval. For example in this case, server A send the PATCH request to server B every 45 seconds. 5. Server B respond to the PATCH request with either HTTP status code 204 or status code 404. 6. If status code is 204, that is OK, server A continues to send the PATCH request using the 45 seconds interval. 7. If the response status is 404, server A have to start the process again from step 1 again to step 6 when 204 status code is received. I have tried to write some code which works but restarting from step 1 when 404 status code is received does not work. Also am not sure if my application design is good enough. Any help and comments about my application design. Below is my code var ( ContentLocation string Timer int32 mu sync.Mutex ) func SendPUTMessageToServerB() { msgbytes, err := ioutil.ReadFile("./msg.json") ... locProfilebytes, err := json.Marshal(pcfprofile) ... locVarNRFUrl := "server B url" profile, resp, err := HandlePUTMessage(locProfilebytes, locVarNRFUrl) status := resp.StatusCode if status == http.StatusOK { logrus.Println("PUT mesage Update SUCCESS") } else if status == http.StatusCreated { logrus.Println("PUT message SUCCESS") } else { logrus.Println(fmt.Errorf("Wrong status code returned by server B %d", status)) } ContentLocation = resp.Header.Get("Location") Timer = profile.TimerValue } func HandlePUTMessage(filebyte []byte, VarPath string) (Profile, *http.Response, error) { var ( // Set client and set url localVarHTTPMethod = http.MethodPut nfp Profile ) req, err := http.NewRequest(localVarHTTPMethod, VarPath, bytes.NewBuffer(filebyte)) if err != nil { logrus.Error(err) } req.Close = true req.Header.Set("Content-Type", "application/json") backoff := 1 for { res, err := Client.Do(req) if err != nil || res == nil { logrus.Println("Server A Trying to send PUT request ...") backoff *= 2 if backoff > 20 { backoff = 20 } time.Sleep(time.Duration(backoff) * time.Second) continue } defer func() { if resCloseErr := res.Body.Close(); resCloseErr != nil { logrus.Errorf("Response body cannot close: %+v", resCloseErr) } }() bodybytes, err := ioutil.ReadAll(res.Body) //localVarHTTPResponse.Body.Close() if err != nil { logrus.Error(err) return nfp, res, err } json.Unmarshal(bodybytes, ) return nfp, res, nil } } // Send PATCH message to server B func PATCHMessage() (err error) { ... patchitembytes, err := json.Marshal(patchitem) ... req, err := http.NewRequest("PATCH", ContentLocation, bytes.NewBuffer(patchitembytes)) req.Header.Set("Content-Type", "application/json-patch+json") response, err := transport.Client.Do(req) // for dev defer response.Body.Close() status := response.StatusCode if status == http.StatusNoContent { logrus.Info("PATCH message SUCCESS") } else if status == http.StatusNotFound { // Here I would like to restart PUT message if status code is 404 logrus.Println("Heart-Beat Message FAILED") } return err } // Send a patch message every Timer value func SendPATCHMessageEveryTimerValue() { for { ticker := time.NewTicker(time.Duration(Timer) * time.Second) mu.Lock() for _ = range ticker.C { err := PATCHMessage() if err != nil { SendPUTMessage() } } mu.Unlock() } } func main() { SendPUTMessageToServerB() go SendPATCHMessageEveryTimerValue() } -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/a2481944-2a5c-467b-ba39-6e355fe219aan%40googlegroups.com.
Re: [go-nuts] How to detect HTTP client stop polling at the server side
Hi, THanks!! BR Abraham On Friday, November 27, 2020 at 11:12:53 AM UTC+2 b.ca...@pobox.com wrote: > On Friday, 27 November 2020 at 06:14:48 UTC Afriyie Abraham Kwabena wrote: > >> What I would like to ask is, using mutex OK and if not the best way of >> solving it, how can i use >> channels in this case. >> > > There's nothing wrong with mutex, but you can use channels for a more > native-Go experience. > This video is well worth watching: > https://www.youtube.com/watch?v=5zXAHh5tJqQ > > In short, you can get mutex or semaphore-like behaviour by having a > channel with fixed depth, and putting/pulling values from it. > Playground <https://play.golang.org/p/Vg-c8v7N0-6> > > mutex := make(chan struct{}, 1) > ... > > mutex <- struct{}{} > ... do stuff > <-mutex > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/e59c6a22-030c-479a-ba8a-b61948307b62n%40googlegroups.com.
Re: [go-nuts] How to detect HTTP client stop polling at the server side
() /home/xxx/go/pkg/mod/golang.org/x/net@v0.0.0-20201031054903-ff519b6c9102/http2/server.go:2152 +0xc5 Previous read at 0x00cf7a88 by goroutine 18: nfnrfapi/services/manag.PollingWorker() /home/xxx/go/src/nfnrfapi/services/manag/api_nf_instance_id_document_Update.go:112 +0x1c4 Goroutine 48 (running) created at: golang.org/x/net/http2.(*serverConn).processHeaders() /home/xxx/go/pkg/mod/golang.org/x/net@v0.0.0-20201031054903-ff519b6c9102/http2/server.go:1882 +0x924 golang.org/x/net/http2.(*serverConn).processFrame() /home/xxx/go/pkg/mod/golang.org/x/net@v0.0.0-20201031054903-ff519b6c9102/http2/server.go:1410 +0x41e golang.org/x/net/http2.(*serverConn).processFrameFromReader() /home/xxx/go/pkg/mod/golang.org/x/net@v0.0.0-20201031054903-ff519b6c9102/http2/server.go:1368 +0x7d9 golang.org/x/net/http2.(*serverConn).serve() /home/xxx/go/pkg/mod/golang.org/x/net@v0.0.0-20201031054903-ff519b6c9102/http2/server.go:869 +0x14fc golang.org/x/net/http2.(*Server).ServeConn() /home/xxx/go/pkg/mod/golang.org/x/net@v0.0.0-20201031054903-ff519b6c9102/http2/server.go:472 +0xdc4 golang.org/x/net/http2.ConfigureServer.func1() /home/xxx/go/pkg/mod/golang.org/x/net@v0.0.0-20201031054903-ff519b6c9102/http2/server.go:298 +0x11e net/http.(*conn).serve() /usr/local/go/src/net/http/server.go:1834 +0x1d5b Goroutine 18 (running) created at: main.main() /home/xxx/go/src/nfnrfapi/main.go:41 +0x2c6 On Friday, November 27, 2020 at 8:14:48 AM UTC+2 Afriyie Abraham Kwabena wrote: > Hi, > > Yes from the warning it prints the handler function below and after google > searching what i did was to mutex.Lock and Unlock the handler function and > no warning again. > However, my google search people mention of using channels instead of > mutex. What I would like to ask is, using mutex OK and if not the best way > of solving it, how can i use > channels in this case. > > Handler function below: > > func UpdateNFInstance(response http.ResponseWriter, request *http.Request) > { > > mu.Lock() > defer mu.Unlock() > > > var ( > localVarHTTPMethod = http.MethodPatch > ctx= context.Background() > > patchItems model.PatchItem > ) > > id := config.GetIdFromRequest(request) > > if request.Method == localVarHTTPMethod { > > if request.Header.Get("Content-Type") != > "application/json-patch+json" { > common.WriteError(response, > common.ErrStatusUnsupportedMediaTypePatch) > return > > } > > err := json.NewDecoder(request.Body).Decode() > if err != nil { > common.WriteError(response, common.ErrBadRequest) > return > } > > defer request.Body.Close() > > delete(idtime, id) // delete value in map if exit > > idtime[id] = time.Now().Unix() > > nfProfile, err := config.Conf.FindNFInstanceProfileById(ctx, id) > if err != nil { > common.WriteError(response, common.ErrNotFound) > return > } > > if patchItems.Path == "/nfStatus" { > > nfProfile.NfStatus = patchItems.Value > nfProfile.LoadTimeStamp = time.Now().String() > > success := config.Conf.UpdateNFInstanceHeartBeatNfStatus(ctx, > nfProfile, id) > if !success { > common.WriteError(response, common.ErrInternalServer) > return > } > > if request.URL.Scheme != "" { > scheme = request.URL.Scheme > } > response.Header().Set("Content-Location", > scheme+"://"+request.Host+request.URL.Path) > response.Header().Set("Response-Desc", "Success") > common.RespondWith3gppJSONPatchJSON(response, > http.StatusNoContent, nil) > > } else { > // patchItems.Path == "/load" information > v, err := strconv.Atoi(patchItems.Value) > if err != nil { > config.Logrus.Errorf("Failed to convert Patch Item Value > string to integer: %s", err.Error()) > } > > nfProfile.Load = int32(v) > nfProfile.LoadTimeStamp = time.Now().String() > > success := config.Conf.UpdateNFInstanceHeartBeatLoad(ctx, > nfProfile, id) > if !success { > common.WriteError(response, common.ErrInternalServer) > return > } > > if request.URL.Scheme != "" { > scheme = re
Re: [go-nuts] How to detect HTTP client stop polling at the server side
Hi, Yes from the warning it prints the handler function below and after google searching what i did was to mutex.Lock and Unlock the handler function and no warning again. However, my google search people mention of using channels instead of mutex. What I would like to ask is, using mutex OK and if not the best way of solving it, how can i use channels in this case. Handler function below: func UpdateNFInstance(response http.ResponseWriter, request *http.Request) { mu.Lock() defer mu.Unlock() var ( localVarHTTPMethod = http.MethodPatch ctx= context.Background() patchItems model.PatchItem ) id := config.GetIdFromRequest(request) if request.Method == localVarHTTPMethod { if request.Header.Get("Content-Type") != "application/json-patch+json" { common.WriteError(response, common.ErrStatusUnsupportedMediaTypePatch) return } err := json.NewDecoder(request.Body).Decode() if err != nil { common.WriteError(response, common.ErrBadRequest) return } defer request.Body.Close() delete(idtime, id) // delete value in map if exit idtime[id] = time.Now().Unix() nfProfile, err := config.Conf.FindNFInstanceProfileById(ctx, id) if err != nil { common.WriteError(response, common.ErrNotFound) return } if patchItems.Path == "/nfStatus" { nfProfile.NfStatus = patchItems.Value nfProfile.LoadTimeStamp = time.Now().String() success := config.Conf.UpdateNFInstanceHeartBeatNfStatus(ctx, nfProfile, id) if !success { common.WriteError(response, common.ErrInternalServer) return } if request.URL.Scheme != "" { scheme = request.URL.Scheme } response.Header().Set("Content-Location", scheme+"://"+request.Host+request.URL.Path) response.Header().Set("Response-Desc", "Success") common.RespondWith3gppJSONPatchJSON(response, http.StatusNoContent, nil) } else { // patchItems.Path == "/load" information v, err := strconv.Atoi(patchItems.Value) if err != nil { config.Logrus.Errorf("Failed to convert Patch Item Value string to integer: %s", err.Error()) } nfProfile.Load = int32(v) nfProfile.LoadTimeStamp = time.Now().String() success := config.Conf.UpdateNFInstanceHeartBeatLoad(ctx, nfProfile, id) if !success { common.WriteError(response, common.ErrInternalServer) return } if request.URL.Scheme != "" { scheme = request.URL.Scheme } response.Header().Set("Content-Location", scheme+"://"+request.Host+request.URL.Path) response.Header().Set("Response-Desc", "Success") common.RespondWith3gppJSONPatchJSON(response, http.StatusNoContent, nil) } } else { common.WriteError(response, common.ErrMethodNotAllowed) return } } BR Abraham On Friday, November 27, 2020 at 6:38:52 AM UTC+2 Shulhan wrote: > > > > On 27 Nov 2020, at 07.06, Afriyie Abraham Kwabena > wrote: > > > > Hi, > > > > Am experiencing data race warning with my pollingworker function below > even though when i build with the -race flag i do not get any error. Any > help? > > > > Usually when you got data race warning it will print the line that cause > read and write race condition. Pay attention to both lines and I think you > will find the cause. > > It's kind of hard to figure it out only through a single function. It > could be in config.Conf or in function that manipulate idtime outside the > pollingworker. > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/9fae8852-b60d-4c76-9939-b997db3d685cn%40googlegroups.com.
Re: [go-nuts] How to detect HTTP client stop polling at the server side
Hi, Am experiancing data race warning with my pollingworker function below even though when i build with the -race flag i do not get any error. Any help? func PollingWorker() { tiker := time.NewTicker(60 * time.Second) for _ = range tiker.C { mu.Lock() for keyid := range idtime { d := time.Now().Unix() - idtime[keyid] if d >= 60 { // Find nfinstance using keyid nfinstanceProfile, err := config.Conf.FindNFInstanceProfileById(ctx, keyid) if err != nil { config.Logrus.Error("Could not find NF Instance Profile with ID :" + keyid + " to SUSPEND Status") } // change nfStatus of nfinstance to SUSPENDED err = config.Conf.SuspendNFInstanceNfStatus(ctx, nfinstanceProfile, keyid) if err != nil { config.Logrus.Error(err) } delete(idtime, keyid) } } mu.Unlock() } } BR Abraham On Wednesday, November 18, 2020 at 10:51:49 AM UTC+2 Afriyie Abraham Kwabena wrote: > Hi Sulhan, Anderson, > > Thanks for your guidance. It works now using time.Ticker > > func worker() { > tiker := time.NewTicker(30 * time.Second) > for _ = range tiker.C { > > mu.Lock() > for keyid := range idtime { > > d := time.Now().Unix() - idtime[keyid] > if d >= 60 { > // delete resouce in database after 60 seconds > _ = DeleteNFInstance(ctx, keyid) > } > } > mu.Unlock() > } > } > > BR > Abraham > > > > On Tuesday, November 17, 2020 at 9:41:01 PM UTC+2 Shulhan wrote: > >> >> >> > On 18 Nov 2020, at 01.06, Afriyie Abraham Kwabena >> wrote: >> > >> > Hi, >> > >> > The UpdateData function is the HTTP handler for the route which matches >> the URL and is called after the mux.Router after receiving an incoming >> request matches the incoming request >> > against the registered route. >> >> ... >> >> > var idtime = make(map[string]int64) >> > >> > >> > func UpdateData(response http.ResponseWriter, request *http.Request) { >> > >> > var ( >> > localVarHTTPMethod = http.MethodPatch >> > patchItems model.PatchItem >> > ) >> > >> > id := config.GetIdFromRequest(request) >> > >> > if request.Method == localVarHTTPMethod { >> > >> > err := json.NewDecoder(request.Body).Decode() >> > if err != nil { >> > common.WriteError(response, common.ErrBadRequest) >> > return >> > } >> > >> > defer request.Body.Close() >> > >> > idtime[id] = time.Now().Unix() >> > >> >> We still may have data race here. >> >> > >> > func worker() { >> > mu.Lock() >> > for keyid := range idtime { >> > >> > d := time.Now().Unix() - idtime[keyid] >> > if d >= 60 { >> > >> > // delete resouce in database after 60 seconds >> > _ = DeleteNFInstance(ctx, keyid) >> > } >> > } >> > mu.Unlock() >> > } >> > >> >> ... >> >> > // main function >> > func main() { >> > r := NewRouter() >> > >> > go worker() >> > >> > >> > fmt.Println("Start listening") >> > fmt.Println(http.ListenAndServe(":8080", r)) >> > } >> > >> > I appreciate your help but am still not able to it work. >> > >> >> Looks like your worker only loop once and then it finished. Either you >> use time.Sleep() to repeat the loop inside loop or use time.Ticker [1]. >> >> [1] https://pkg.go.dev/time#Ticker >> >> -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/9db5a074-0b0a-4f3a-ab20-7c5d67f458a0n%40googlegroups.com.
Re: [go-nuts] How to detect if transport connection break
Hi, Yes, that is what intend to implement. Can you help with some information about how I could implement it. If possible some libraries or example code. Abraham On Friday, November 20, 2020 at 1:07:12 PM UTC+2 Afriyie Abraham Kwabena wrote: > Hi, > > Am new to programming and if you could explain further what you mean by > long lived process. > > > On Friday, November 20, 2020 at 11:41:42 AM UTC+2 amits...@gmail.com > wrote: > >> >> >> On Fri, 20 Nov 2020, 7:51 pm Afriyie Abraham Kwabena, < >> afriyie...@gmail.com> wrote: >> >>> >>> Hi, >>> >>> My basic understanding of HTTP protocol is that an HTTP client sent >>> request, get response from the HTTP server and then the connection is >>> closed. >>> >>> My question is how can an HTTP client detect if the underling transport >>> connection break. For example if the HTTP server shutdown, is there a way >>> to detect that at the client so that the client can start a persistent >>> request. >>> >>> If possible, how can I do that in golang HTTP client? >>> >> >> Are you thinking about implementing a connection pool for your long lived >> process? >> >> >> >>> BR >>> Abraham >>> >>> >>> -- >>> You received this message because you are subscribed to the Google >>> Groups "golang-nuts" group. >>> To unsubscribe from this group and stop receiving emails from it, send >>> an email to golang-nuts...@googlegroups.com. >>> To view this discussion on the web visit >>> https://groups.google.com/d/msgid/golang-nuts/4937b529-c1aa-4425-8b81-01214c1fc1f7n%40googlegroups.com >>> >>> <https://groups.google.com/d/msgid/golang-nuts/4937b529-c1aa-4425-8b81-01214c1fc1f7n%40googlegroups.com?utm_medium=email_source=footer> >>> . >>> >> -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/d2125284-5529-4c95-82c7-3a8dac7fde78n%40googlegroups.com.
Re: [go-nuts] How to detect if transport connection break
Hi, Am new to programming and if you could explain further what you mean by long lived process. On Friday, November 20, 2020 at 11:41:42 AM UTC+2 amits...@gmail.com wrote: > > > On Fri, 20 Nov 2020, 7:51 pm Afriyie Abraham Kwabena, < > afriyie...@gmail.com> wrote: > >> >> Hi, >> >> My basic understanding of HTTP protocol is that an HTTP client sent >> request, get response from the HTTP server and then the connection is >> closed. >> >> My question is how can an HTTP client detect if the underling transport >> connection break. For example if the HTTP server shutdown, is there a way >> to detect that at the client so that the client can start a persistent >> request. >> >> If possible, how can I do that in golang HTTP client? >> > > Are you thinking about implementing a connection pool for your long lived > process? > > > >> BR >> Abraham >> >> >> -- >> You received this message because you are subscribed to the Google Groups >> "golang-nuts" group. >> To unsubscribe from this group and stop receiving emails from it, send an >> email to golang-nuts...@googlegroups.com. >> To view this discussion on the web visit >> https://groups.google.com/d/msgid/golang-nuts/4937b529-c1aa-4425-8b81-01214c1fc1f7n%40googlegroups.com >> >> <https://groups.google.com/d/msgid/golang-nuts/4937b529-c1aa-4425-8b81-01214c1fc1f7n%40googlegroups.com?utm_medium=email_source=footer> >> . >> > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/ce2735a8-68e7-47e1-9eb4-59a825b1eb94n%40googlegroups.com.
[go-nuts] How to detect if transport connection break
Hi, My basic understanding of HTTP protocol is that an HTTP client sent request, get response from the HTTP server and then the connection is closed. My question is how can an HTTP client detect if the underling transport connection break. For example if the HTTP server shutdown, is there a way to detect that at the client so that the client can start a persistent request. If possible, how can I do that in golang HTTP client? BR Abraham -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4937b529-c1aa-4425-8b81-01214c1fc1f7n%40googlegroups.com.
Re: [go-nuts] How to detect HTTP client stop polling at the server side
Hi Sulhan, Anderson, Thanks for your guidance. It works now using time.Ticker func worker() { tiker := time.NewTicker(30 * time.Second) for _ = range tiker.C { mu.Lock() for keyid := range idtime { d := time.Now().Unix() - idtime[keyid] if d >= 60 { // delete resouce in database after 60 seconds _ = DeleteNFInstance(ctx, keyid) } } mu.Unlock() } } BR Abraham On Tuesday, November 17, 2020 at 9:41:01 PM UTC+2 Shulhan wrote: > > > > On 18 Nov 2020, at 01.06, Afriyie Abraham Kwabena > wrote: > > > > Hi, > > > > The UpdateData function is the HTTP handler for the route which matches > the URL and is called after the mux.Router after receiving an incoming > request matches the incoming request > > against the registered route. > > ... > > > var idtime = make(map[string]int64) > > > > > > func UpdateData(response http.ResponseWriter, request *http.Request) { > > > > var ( > > localVarHTTPMethod = http.MethodPatch > > patchItems model.PatchItem > > ) > > > > id := config.GetIdFromRequest(request) > > > > if request.Method == localVarHTTPMethod { > > > > err := json.NewDecoder(request.Body).Decode() > > if err != nil { > > common.WriteError(response, common.ErrBadRequest) > > return > > } > > > > defer request.Body.Close() > > > > idtime[id] = time.Now().Unix() > > > > We still may have data race here. > > > > > func worker() { > > mu.Lock() > > for keyid := range idtime { > > > > d := time.Now().Unix() - idtime[keyid] > > if d >= 60 { > > > > // delete resouce in database after 60 seconds > > _ = DeleteNFInstance(ctx, keyid) > > } > > } > > mu.Unlock() > > } > > > > ... > > > // main function > > func main() { > > r := NewRouter() > > > > go worker() > > > > > > fmt.Println("Start listening") > > fmt.Println(http.ListenAndServe(":8080", r)) > > } > > > > I appreciate your help but am still not able to it work. > > > > Looks like your worker only loop once and then it finished. Either you use > time.Sleep() to repeat the loop inside loop or use time.Ticker [1]. > > [1] https://pkg.go.dev/time#Ticker > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/cc7b885f-074a-4b23-9f4c-08d4a3a7ac62n%40googlegroups.com.
Re: [go-nuts] How to detect HTTP client stop polling at the server side
Hi, The UpdateData function is the HTTP handler for the route which matches the URL and is called after the mux.Router after receiving an incoming request matches the incoming request against the registered route. BR Afriyie On Tuesday, November 17, 2020 at 7:33:50 PM UTC+2 Afriyie Abraham Kwabena wrote: > Hi, > > I have made changes according to the comments and also simply the main > function but am not sure if the worker go routine works. > This what i did: > > type Route struct { > Namestring > Method string > Pattern string > HandlerFunc http.HandlerFunc > } > > var idtime = make(map[string]int64) > > > func UpdateData(response http.ResponseWriter, request *http.Request) { > > var ( > localVarHTTPMethod = http.MethodPatch > patchItems model.PatchItem > ) > > id := config.GetIdFromRequest(request) > > if request.Method == localVarHTTPMethod { > > err := json.NewDecoder(request.Body).Decode() > if err != nil { > common.WriteError(response, common.ErrBadRequest) > return > } > > defer request.Body.Close() > > idtime[id] = time.Now().Unix() > > > common.RespondWith3gppJsonPatchJson(response, > http.StatusNoContent, nil) > } else { > common.WriteError(response, common.ErrMethodNotAllowed) > return > } > } > > var ( > mu sync.Mutex > ctx = context.Background() > ) > > func worker() { > mu.Lock() > for keyid := range idtime { > > d := time.Now().Unix() - idtime[keyid] > if d >= 60 { > > // delete resouce in database after 60 seconds > _ = DeleteNFInstance(ctx, keyid) > } > } > mu.Unlock() > } > > // Delete info > func DeleteNFInstance(ctx context.Context, nfinstanceId string) bool { > filter := bson.M{"_id": nfinstanceId} > _, err := db.Collection(COLLECTION).DeleteOne(ctx, filter) > if err != nil { > return false > } > return true > } > > type Routes []Route > > func NewRouter() *mux.Router { > router := mux.NewRouter().StrictSlash(true) > for _, route := range routes { > var handler http.Handler > handler = route.HandlerFunc > > router. > Methods(route.Method). > Path(route.Pattern). > Name(route.Name). > Handler(handler) > } > > return router > } > > var routes = Routes{ > > Route{ > "UpdateData", > strings.ToUpper("Patch"), > "/users/{id}", > UpdateData, > }, > } > > // main function > func main() { > r := NewRouter() > > go worker() > > > fmt.Println("Start listening") > fmt.Println(http.ListenAndServe(":8080", r)) > } > > I appreciate your help but am still not able to it work. > > > On Tuesday, November 17, 2020 at 3:48:44 PM UTC+2 Shulhan wrote: > >> Hi Afriyie, >> >> Looks like you almost there ;) >> >> > On 17 Nov 2020, at 20.11, Afriyie Abraham Kwabena >> wrote: >> > >> > HI, >> > >> > This is what I have tried so far but am not able to get the time >> difference in seconds. I mean the time differences between the time stored >> in the map[string]time.Time and >> > the current time in seconds. >> > >> > code: >> > >> > type Server struct { >> > idtime map[string]time.Time >> > } >> > >> > var my = Server{} >> > >> > func main() { >> > r := mux.NewRouter() >> > usersData := r.PathPrefix("/users").Subrouter() >> > >> usersData.Path("/{id}").Methods(http.MethodPatch).HandlerFunc(UpdateData) >> > >> >> Based on my understanding (I have never use mux before), the UpdateDate >> function will be running concurrently as goroutine. Lets say that we have >> three PATCH requests at the same time, there will be three UpdateData >> running concurrently or in parallel. >> >> > fmt.Println("Start listening") >> > fmt.Println(http.ListenAndServe(":8080", r)) >> > } >> > >> > func UpdateData(response http.ResponseWriter, request *http.Request) { >> > >> > var ( >> > localVarHTTPMethod = http.MethodPatch >> > patchItems model.PatchIte
Re: [go-nuts] How to detect HTTP client stop polling at the server side
Hi, I have made changes according to the comments and also simply the main function but am not sure if the worker go routine works. This what i did: type Route struct { Namestring Method string Pattern string HandlerFunc http.HandlerFunc } var idtime = make(map[string]int64) func UpdateData(response http.ResponseWriter, request *http.Request) { var ( localVarHTTPMethod = http.MethodPatch patchItems model.PatchItem ) id := config.GetIdFromRequest(request) if request.Method == localVarHTTPMethod { err := json.NewDecoder(request.Body).Decode() if err != nil { common.WriteError(response, common.ErrBadRequest) return } defer request.Body.Close() idtime[id] = time.Now().Unix() common.RespondWith3gppJsonPatchJson(response, http.StatusNoContent, nil) } else { common.WriteError(response, common.ErrMethodNotAllowed) return } } var ( mu sync.Mutex ctx = context.Background() ) func worker() { mu.Lock() for keyid := range idtime { d := time.Now().Unix() - idtime[keyid] if d >= 60 { // delete resouce in database after 60 seconds _ = DeleteNFInstance(ctx, keyid) } } mu.Unlock() } // Delete info func DeleteNFInstance(ctx context.Context, nfinstanceId string) bool { filter := bson.M{"_id": nfinstanceId} _, err := db.Collection(COLLECTION).DeleteOne(ctx, filter) if err != nil { return false } return true } type Routes []Route func NewRouter() *mux.Router { router := mux.NewRouter().StrictSlash(true) for _, route := range routes { var handler http.Handler handler = route.HandlerFunc router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(handler) } return router } var routes = Routes{ Route{ "UpdateData", strings.ToUpper("Patch"), "/users/{id}", UpdateData, }, } // main function func main() { r := NewRouter() go worker() fmt.Println("Start listening") fmt.Println(http.ListenAndServe(":8080", r)) } I appreciate your help but am still not able to it work. On Tuesday, November 17, 2020 at 3:48:44 PM UTC+2 Shulhan wrote: > Hi Afriyie, > > Looks like you almost there ;) > > > On 17 Nov 2020, at 20.11, Afriyie Abraham Kwabena > wrote: > > > > HI, > > > > This is what I have tried so far but am not able to get the time > difference in seconds. I mean the time differences between the time stored > in the map[string]time.Time and > > the current time in seconds. > > > > code: > > > > type Server struct { > > idtime map[string]time.Time > > } > > > > var my = Server{} > > > > func main() { > > r := mux.NewRouter() > > usersData := r.PathPrefix("/users").Subrouter() > > usersData.Path("/{id}").Methods(http.MethodPatch).HandlerFunc(UpdateData) > > > > Based on my understanding (I have never use mux before), the UpdateDate > function will be running concurrently as goroutine. Lets say that we have > three PATCH requests at the same time, there will be three UpdateData > running concurrently or in parallel. > > > fmt.Println("Start listening") > > fmt.Println(http.ListenAndServe(":8080", r)) > > } > > > > func UpdateData(response http.ResponseWriter, request *http.Request) { > > > > var ( > > localVarHTTPMethod = http.MethodPatch > > patchItems model.PatchItem > > ) > > > > id := config.GetIdFromRequest(request) > > > > if request.Method == localVarHTTPMethod { > > > > err := json.NewDecoder(request.Body).Decode() > > if err != nil { > > common.WriteError(response, common.ErrBadRequest) > > return > > } > > > > defer request.Body.Close() > > > > my.idtime = make(map[string]time.Time) > > Since the UpdateData is running independently for each request, you should > initialize this once, in the main, otherwise each UpdateData routine will > reset the idtime variable. > > > my.idtime[id] = time.Now() > > > > go func() { > > for keyid, t := range my.idtime { > > > > ts := t.Format(time.RFC3339) > > > > v, err := time.Parse(time.RFC3339, ts) > > if err != nil { > > fmt.Println(err) > > os.Exit(1) > > } > > > > timeRemaining := getTimeRemaining(v) > > > > if timeRemaining.S >= 60 { > > // delete resouce in database after 60 seconds >
Re: [go-nuts] How to detect HTTP client stop polling at the server side
HI, This is what I have tried so far but am not able to get the time difference in seconds. I mean the time differences between the time stored in the map[string]time.Time and the current time in seconds. code: type Server struct { idtime map[string]time.Time } var my = Server{} func main() { r := mux.NewRouter() usersData := r.PathPrefix("/users").Subrouter() usersData.Path("/{id}").Methods(http.MethodPatch).HandlerFunc(UpdateData) fmt.Println("Start listening") fmt.Println(http.ListenAndServe(":8080", r)) } func UpdateData(response http.ResponseWriter, request *http.Request) { var ( localVarHTTPMethod = http.MethodPatch patchItems model.PatchItem ) id := config.GetIdFromRequest(request) if request.Method == localVarHTTPMethod { err := json.NewDecoder(request.Body).Decode() if err != nil { common.WriteError(response, common.ErrBadRequest) return } defer request.Body.Close() my.idtime = make(map[string]time.Time) my.idtime[id] = time.Now() go func() { for keyid, t := range my.idtime { ts := t.Format(time.RFC3339) v, err := time.Parse(time.RFC3339, ts) if err != nil { fmt.Println(err) os.Exit(1) } timeRemaining := getTimeRemaining(v) if timeRemaining.S >= 60 { // delete resouce in database after 60 seconds deleteResourceUsingIdkey(keyid) } } }() common.RespondWith3gppJsonPatchJson(response, http.StatusNoContent, nil) } else { common.WriteError(response, common.ErrMethodNotAllowed) return } } type count struct { S int } func getTimeRemaining(t time.Time) count { currentTime := time.Now() difference := t.Sub(currentTime) seconds := int(difference.Seconds()) return count{ S: seconds, } } func deleteResourceUsingIdkey(idkey string) { // do delete here } Any help. On Tuesday, November 17, 2020 at 10:34:39 AM UTC+2 Anderson Queiroz wrote: > Just one thing to keep in mind. Likely you have more than one serve > instance running to process the requests. Thus it might happen the client > will poll a different server on every request. Just imagine you have > servers A, B, C behind a load balance and the domain example.com. As the > client is pooling example.com, the first request might reach A, the > second B and the third C. Now you have the 3 servers tracking the same > client. It might happen server A doesn't receive any request from the > client for a while, but not because the client isn't pooling any more, but > because all requests are being directed to either B or C. > > On Tuesday, 17 November 2020 at 07:12:18 UTC+1 Shulhan wrote: > >> >> >> > On 16 Nov 2020, at 16.24, Afriyie Abraham Kwabena >> wrote: >> > >> > Hi , >> > >> > You are right but am new to programming and currently this what i have >> done. >> > I have an http server handler that receives the PATCH request and >> stores the id and the current time stamp of the request. >> > But my problem is how to write the worker function to do the clean up >> every X seconds. >> > >> > Code: >> > func UpdateData(response http.ResponseWriter, request *http.Request) { >> > >> > var ( >> > localVarHTTPMethod = http.MethodPatch >> > patchItems model.PatchItem >> > ) >> > >> > id := config.GetIdFromRequest(request) >> > >> > if request.Method == localVarHTTPMethod { >> > >> > err := json.NewDecoder(request.Body).Decode() >> > if err != nil { >> > common.WriteError(response, common.ErrBadRequest) >> > return >> > } >> > >> > defer request.Body.Close() >> > >> > var idtime = make(map[string]string) >> > >> > delete(idtime, id) // delete if already exist >> > idtime[id] = time.Now() // store id and time stamp in map >> >> You should store idtime inside the server/service type (the one that have >> HTTP handlers). For example, >> >> >> type Server struct { >> idtime map[string]string >> } >> >> func (my *Server) UpdateData(...) { >> ... >> my.idtime[id] = time.Now() >> ... >> } >> >> >> > >> > // how do i write a worker to the clean up after every X seconds? >> > >> >> Create a function that loop forever and l
Re: [go-nuts] How to detect HTTP client stop polling at the server side
Hi , You are right but am new to programming and currently this what i have done. I have an http server handler that receives the PATCH request and stores the id and the current time stamp of the request. But my problem is how to write the worker function to do the clean up every X seconds. Code: func UpdateData(response http.ResponseWriter, request *http.Request) { var ( localVarHTTPMethod = http.MethodPatch patchItems model.PatchItem ) id := config.GetIdFromRequest(request) if request.Method == localVarHTTPMethod { err := json.NewDecoder(request.Body).Decode() if err != nil { common.WriteError(response, common.ErrBadRequest) return } defer request.Body.Close() var idtime = make(map[string]string) delete(idtime, id) // delete if already exist idtime[id] = time.Now() // store id and time stamp in map // how do i write a worker to the clean up after every X seconds? } else { common.WriteError(response, common.ErrMethodNotAllowed) return } } BR Abraham On Sunday, November 15, 2020 at 9:01:27 AM UTC+2 Shulhan wrote: > > > On 14 Nov 2020, at 20.06, Afriyie Abraham Kwabena > wrote: > > > > Hi, > > > > My question is about multiple HTTP client polling an HTTP server > randomly with a PATCH request to update a resource at the server running in > front of MongoDB. The clients poll with their different ids and a valid > time in their request. At the server, I can keep their ids and their > different times. > > How can detect at the server if a specific client stop polling. I would > like to write a function that detect at the HTTP server if a specific > client stop polling and then remove its resources after some time from a > database. Am using gorilla/mux package for the server. Any help, am new to > Golang programming. > > > > I think this is not Go specific, but more like engineering in general. > > My suggestion is you can store the last time when user request to PATCH > endpoint in some storage or internal memory (like map[userID]timestamp) and > then have some worker that check the timestamp to clean it up every X > seconds or minutes. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/7798fe2c-d176-4514-8fe0-04b6e19f4399n%40googlegroups.com.
[go-nuts] How to detect HTTP client stop polling at the server side
Hi, My question is about multiple HTTP client polling an HTTP server randomly with a PATCH request to update a resource at the server running in front of MongoDB. The clients poll with their different ids and a valid time in their request. At the server, I can keep their ids and their different times. How can detect at the server if a specific client stop polling. I would like to write a function that detect at the HTTP server if a specific client stop polling and then remove its resources after some time from a database. Am using gorilla/mux package for the server. Any help, am new to Golang programming. Thanks in advance -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/8658410c-5cac-4dff-80e3-ebb1b8bbb5een%40googlegroups.com.
[go-nuts] How to query mongodb
Hi I have in my collection this JSON { "allowedSnssaiList": [ { "allowedSnssai": { "sst": 1, "sd": "1" }, "allowedSnssai": { "sst": 2, "sd": "3" } } ] } how can query using the key sst and sd to return a documents matching the two exact values? Example when i query using sst:1, sd :1 it should return the documents but sst:1 and sd:3 should not. The problem am having is that when i query using "find" using sst:1, sd:3 it still return this JSON. br Abraham -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/32eb3edb-d9c0-4c17-a4d0-2df0014b47cc%40googlegroups.com.
[go-nuts] Re: How to query mongodb dynamically using Go interface
Hi, The problem wa about the index, i solved it by using the right index bson.M{"amfInfo.taiList.tac": args[2]} since the fuction is called Da.FindIp(targetNfType, sst, sd, tac) Thanks! On Thursday, January 16, 2020 at 5:04:40 PM UTC+2, Afriyie Abraham Kwabena wrote: > > Hi, > > I have been trying to create a dynamic mongodb query using golang > interface but the logical $or does not work. > It only return a documents when the input matches the > bson.M{"sNssais.sst": args[0].(int32), "sNssais.sd": args[1].(string)}. > other matches like bson.M{"amfInfo.taiList.tac": args}, etc does not work > even though a document in mongodb collection exist that matches the input > value. > Any idea as how to do this? The function is as below > > func (m *NfInstanceDataAccess) FindIp(preferredNfInstances string, args > ...interface{}) ([]model.NfProfile, bool) { > var ip []model.NfProfile > pipeline := bson.M{ > "nfType": preferredNfInstances, > "$or": []interface{}{ > bson.M{"sNssais.sst": args[0].(int32), "sNssais.sd": > args[1].(string)}, > bson.M{"amfInfo.taiList.tac": args}, > bson.M{"smfInfo.taiList.tac": args}, > bson.M{"upfInfo.taiList.tac": args}, > }, > } > filter := bson.M{"ipv4Addresses": true} > err := db.C(COLLECTION).Find(pipeline).Select(filter).All() > if err != nil { > return ip, false > } > return ip, true > } > > > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/1ee05646-077e-4e21-b9ee-3ac59cdd4e45%40googlegroups.com.
[go-nuts] Re: How to query mongodb dynamically using Go interface
Hi, this is the JSON document in mongodb. { "sNssais": [{ "sst": 0, "sd": "string" }], "nsiList": [ "string" ], "ipv4Addresses": [ "198.51.100.1" ], "ipv6Addresses": [ "2001:db8:85a3::8a2e:370:7334" ], "amfInfo": { "amfSetId": "string", "taiList": [{ "plmnId": { "mcc": "string", "mnc": "string" }, "tac": "3022", "nid": "string" }], }, "customInfo": {} } The args in the *.tac are string values, even if i set the type casting like bson.M{"amfInfo.taiList.tac": args[0].(string)} it stiil do not match "3022" args input. And yes, am looking for exact match. On Thursday, January 16, 2020 at 5:04:40 PM UTC+2, Afriyie Abraham Kwabena wrote: > > Hi, > > I have been trying to create a dynamic mongodb query using golang > interface but the logical $or does not work. > It only return a documents when the input matches the > bson.M{"sNssais.sst": args[0].(int32), "sNssais.sd": args[1].(string)}. > other matches like bson.M{"amfInfo.taiList.tac": args}, etc does not work > even though a document in mongodb collection exist that matches the input > value. > Any idea as how to do this? The function is as below > > func (m *NfInstanceDataAccess) FindIp(preferredNfInstances string, args > ...interface{}) ([]model.NfProfile, bool) { > var ip []model.NfProfile > pipeline := bson.M{ > "nfType": preferredNfInstances, > "$or": []interface{}{ > bson.M{"sNssais.sst": args[0].(int32), "sNssais.sd": > args[1].(string)}, > bson.M{"amfInfo.taiList.tac": args}, > bson.M{"smfInfo.taiList.tac": args}, > bson.M{"upfInfo.taiList.tac": args}, > }, > } > filter := bson.M{"ipv4Addresses": true} > err := db.C(COLLECTION).Find(pipeline).Select(filter).All() > if err != nil { > return ip, false > } > return ip, true > } > > > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/37f74556-974f-4229-bd2f-6850bfa62620%40googlegroups.com.
[go-nuts] How to query mongodb dynamically using Go interface
Hi, I have been trying to create a dynamic mongodb query using golang interface but the logical $or does not work. It only return a documents when the input matches the bson.M{"sNssais.sst": args[0].(int32), "sNssais.sd": args[1].(string)}. other matches like bson.M{"amfInfo.taiList.tac": args}, etc does not work even though a document in mongodb collection exist that matches the input value. Any idea as how to do this? The function is as below func (m *NfInstanceDataAccess) FindIp(preferredNfInstances string, args ...interface{}) ([]model.NfProfile, bool) { var ip []model.NfProfile pipeline := bson.M{ "nfType": preferredNfInstances, "$or": []interface{}{ bson.M{"sNssais.sst": args[0].(int32), "sNssais.sd": args[1].(string)}, bson.M{"amfInfo.taiList.tac": args}, bson.M{"smfInfo.taiList.tac": args}, bson.M{"upfInfo.taiList.tac": args}, }, } filter := bson.M{"ipv4Addresses": true} err := db.C(COLLECTION).Find(pipeline).Select(filter).All() if err != nil { return ip, false } return ip, true } -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/c2dca0c6-e3f7-4822-9b7f-b09102450293%40googlegroups.com.
Re: [go-nuts] How to use .toml file to parse IP address and port to http server
Hi, I have solve the problem and it works now. Thanks. On Monday, September 30, 2019 at 11:06:20 AM UTC+3, Afriyie Abraham Kwabena wrote: > > Hi, > > I have applied similar scenario to the function below but am not getting > the Ip address and the port number. Below is the function > > var addr string > > func init(){ > > var conf Config > if _, err := toml.Decode("config.toml", ); err != nil { > // handle error > } > addr = net.JoinHostPort(conf.Addr, conf.Port) > fmt.Println(addr) // This printing empty > > } > > > func main() { > > server := NewServer() > > go func() { > > if err := > server.ListenAndServeTLS("/home/cumucore/diam/server.crt", > "/home/cumucore/diam/server.key"); err != nil && err != > http.ErrServerClosed { > logger.Fatalf("Could not listen on %s: %v\n", addr, err) > > if err := server.ListenAndServe(); err != nil { > logger.Fatalf("Could not listen on %s: %v\n", addr, err) > } > > } > }() > } > > > // Create a new server > func NewServer() *http.Server { > > return { > Addr: addr, > Handler: diam.NewRouter(), > ErrorLog: logger, > ReadTimeout: 5 * time.Second, > WriteTimeout: 10 * time.Second, > IdleTimeout: 15 * time.Second, > } > } > > Ther config.toml file contain the key values as > Addr = "192.168.9.186" > Port = "8000" > > What might be the problem in this case > > > On Sunday, September 29, 2019 at 5:18:55 PM UTC+3, Andrew Pillar wrote: >> >> Use net.JoinHostPort to concatenate the values you have in the struct >> and pass the to http.Server struct. >> >> if _, err := toml.Decode("config.toml", ); err != nil { >> // handle error >> } >> >> addr, err := net.JoinHostPort(conf.Address, conf.PORT) >> >> if err != nil { >> // handle error >> } >> >> src := { >> Addr: addr, >> } >> >> Be sure to set explicit struct tags on your destination struct that >> will be used for unmarshalling the toml. This way the decoder will know >> which struct fields to populate. >> >> type Config struct { >> PORTstring `toml:"port"` >> Address string `toml:"address"` >> } >> >> This will only be necessary though if you want the fields to map >> differently depending on their name. >> >> -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/28360a86-da47-4226-90f2-59515a317210%40googlegroups.com.
Re: [go-nuts] How to use .toml file to parse IP address and port to http server
Hi, I have applied similar scenario to the function below but am not getting the Ip address and the port number. Below is the function var addr string func init(){ var conf Config if _, err := toml.Decode("config.toml", ); err != nil { // handle error } addr = net.JoinHostPort(conf.Addr, conf.Port) fmt.Println(addr) // This printing empty } func main() { server := NewServer() go func() { if err := server.ListenAndServeTLS("/home/cumucore/diam/server.crt", "/home/cumucore/diam/server.key"); err != nil && err != http.ErrServerClosed { logger.Fatalf("Could not listen on %s: %v\n", addr, err) if err := server.ListenAndServe(); err != nil { logger.Fatalf("Could not listen on %s: %v\n", addr, err) } } }() } // Create a new server func NewServer() *http.Server { return { Addr: addr, Handler: diam.NewRouter(), ErrorLog: logger, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 15 * time.Second, } } Ther config.toml file contain the key values as Addr = "192.168.9.186" Port = "8000" What might be the problem in this case On Sunday, September 29, 2019 at 5:18:55 PM UTC+3, Andrew Pillar wrote: > > Use net.JoinHostPort to concatenate the values you have in the struct > and pass the to http.Server struct. > > if _, err := toml.Decode("config.toml", ); err != nil { > // handle error > } > > addr, err := net.JoinHostPort(conf.Address, conf.PORT) > > if err != nil { > // handle error > } > > src := { > Addr: addr, > } > > Be sure to set explicit struct tags on your destination struct that > will be used for unmarshalling the toml. This way the decoder will know > which struct fields to populate. > > type Config struct { > PORTstring `toml:"port"` > Address string `toml:"address"` > } > > This will only be necessary though if you want the fields to map > differently depending on their name. > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/9756a565-79c7-4eda-96f3-172e3ec6a908%40googlegroups.com.
[go-nuts] How to use .toml file to parse IP address and port to http server
Hi, How I can use the .toml file to parse IP address and port to simple http server instead of using flags I have a config.toml file which contains these parameters in PORT = "8000" Address = "localhost" //Parameters type struct as type Config struct { PORTstring Address string } I can load file in main function as var conf Config if _, err := toml.Decode("config.toml", ); err != nil { // handle error } //simple http server main function func main() { var dir string flag.StringVar(, "dir", ".", "the directory to serve files from. Defaults to the current dir") flag.Parse() r := mux.NewRouter() // This will serve files under http://localhost:8000/static/ r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir srv := { Handler: r, Addr: "127.0.0.1:8000", WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } log.Fatal(srv.ListenAndServe()) } Any help? -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/f095834a-5bde-4ae2-93dd-5f2f39212aa2%40googlegroups.com.
[go-nuts] How to search for string value in array
I have trying to write a function that will accept a string as an input and return another string in a slice but it not working. I have function that unmarshal udp response to a type AuthVectors and then append the type struct data into an array authVecSlice. Below is the code type AuthVectors struct { MessageType string `json:"message_type"` IMSIstring `json:"IMSI"` RANDstring `json:"RAND"` XRESstring `json:"XRES"` AUTNstring `json:"AUTN"` } var imsistr = "2443411" var authVecSlice = make([]AuthVectors, 10) func getAuthVec() { hostName := "localhost" portNum := "4343" service := hostName + ":" + portNum RemoteAddr, err := net.ResolveUDPAddr("udp", service) conn, err := net.DialUDP("udp", nil, RemoteAddr) if err != nil { log.Fatal(err) } defer conn.Close() // write a message to server _, err = conn.Write([]byte(imsistr)) if err != nil { log.Println(err) } // receive message from server buffer := make([]byte, 1024) i, _, err := conn.ReadFromUDP(buffer) checkError(err) err = json.Unmarshal(buffer[:i], ) if err != nil { panic(err) } authVecSlice = append(authVecSlice, avs) fmt.Println(authVecSlice) } The array out put is as follows [{AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} {AUTN_PARAM 2443411 211B025CB1CC8EE9CBB5FC7F56C1506B C9396A5AC7E68D62 31D...} {AUTN_PARAM 2443411 7D2A8C6E6B5CA243278987DFAF7FC829 C9EE960D0F5A501A 7E8..} ...] I would like to use the field RAND to search and return the corresponding XRES in the array. For example in the array is {AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} I would like to use the RAND value for example C98FC7C6DE9E1351A397D0AF99B6E890 as a search string and return its corresponding XRES D857E39D57E5E6BE. func getXRES(a []AuthVectors, x interface{}) (xres string) { for _, v := range a { if x == v { xres := v.XRES return xres } } return "Item not found" } The problem for me is that the array value do not have key to be use to perform the search. All example I found involves the use of key to fetch the values. Any help -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/ca9a0f00-9fdc-4383-b58a-31780d0ae45d%40googlegroups.com.
[go-nuts] How to search for string value in array
I have trying to write a function that will accept a string as an input and return another string in a slice but it not working. I have function that unmarshal udp response to a type AuthVectors and then append the type struct data into an array authVecSlice. Below is the code type AuthVectors struct { MessageType string `json:"message_type"` IMSIstring `json:"IMSI"` RANDstring `json:"RAND"` XRESstring `json:"XRES"` AUTNstring `json:"AUTN"` } var imsistr = "2443411" var authVecSlice = make([]AuthVectors, 10) func getAuthVec() { hostName := "localhost" portNum := "4343" service := hostName + ":" + portNum RemoteAddr, err := net.ResolveUDPAddr("udp", service) conn, err := net.DialUDP("udp", nil, RemoteAddr) if err != nil { log.Fatal(err) } defer conn.Close() // write a message to server _, err = conn.Write([]byte(imsistr)) if err != nil { log.Println(err) } // receive message from server buffer := make([]byte, 1024) i, _, err := conn.ReadFromUDP(buffer) checkError(err) err = json.Unmarshal(buffer[:i], ) if err != nil { panic(err) } authVecSlice = append(authVecSlice, avs) fmt.Println(authVecSlice) } The array out put is as follows [{AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} {AUTN_PARAM 2443411 211B025CB1CC8EE9CBB5FC7F56C1506B C9396A5AC7E68D62 31D...} {AUTN_PARAM 2443411 7D2A8C6E6B5CA243278987DFAF7FC829 C9EE960D0F5A501A 7E8..} ...] I would like to use the field RAND to search and return the corresponding XRES in the array. For example in the array is {AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} I would like to use the RAND value for example C98FC7C6DE9E1351A397D0AF99B6E890 as a search string and return its corresponding XRES D857E39D57E5E6BE. func getXRES(a []AuthVectors, x interface{}) (xres string) { for _, v := range a { if x == v { xres := v.XRES return xres } } return "Item not found" } The problem for me is that the array value do not have key to be use to perform the search. All example I found involves the use of key to fetch the values. Any help -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/42adcb63-ca63-4bc1-ad6f-5eeb64542d46%40googlegroups.com.
[go-nuts] How to search for string value in array
I have trying to write a function that will accept a string as an input and return another string in a slice but it not working. I have function that unmarshal udp response to a type AuthVectors and then append the type struct data into an array authVecSlice. Below is the code type AuthVectors struct { MessageType string `json:"message_type"` IMSIstring `json:"IMSI"` RANDstring `json:"RAND"` XRESstring `json:"XRES"` AUTNstring `json:"AUTN"` } var imsistr = "2443411" var authVecSlice = make([]AuthVectors, 10) func getAuthVec() { hostName := "localhost" portNum := "4343" service := hostName + ":" + portNum RemoteAddr, err := net.ResolveUDPAddr("udp", service) conn, err := net.DialUDP("udp", nil, RemoteAddr) if err != nil { log.Fatal(err) } defer conn.Close() // write a message to server _, err = conn.Write([]byte(imsistr)) if err != nil { log.Println(err) } // receive message from server buffer := make([]byte, 1024) i, _, err := conn.ReadFromUDP(buffer) checkError(err) err = json.Unmarshal(buffer[:i], ) if err != nil { panic(err) } authVecSlice = append(authVecSlice, avs) fmt.Println(authVecSlice) } The array out put is as follows [{AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} {AUTN_PARAM 2443411 211B025CB1CC8EE9CBB5FC7F56C1506B C9396A5AC7E68D62 31D...} {AUTN_PARAM 2443411 7D2A8C6E6B5CA243278987DFAF7FC829 C9EE960D0F5A501A 7E8..} ...] I would like to use the field RAND to search and return the corresponding XRES in the array. For example in the array is {AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} I would like to use the RAND value for example C98FC7C6DE9E1351A397D0AF99B6E890 as a search string and return its corresponding XRES D857E39D57E5E6BE. func getXRES(a []AuthVectors, x interface{}) (xres string) { for _, v := range a { if x == v { xres := v.XRES return xres } } return "Item not found" } The problem for me is that the array value do not have key to be use to perform the search. All example I found involves the use of key to fetch the values. Any help -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/5ca278a8-e5ec-45ff-a056-018e57fa2d49%40googlegroups.com.
[go-nuts] How to search for string value in array
I have trying to write a function that will accept a string as an input and return another string in a slice but it not working. I have function that unmarshal udp response to a type AuthVectors and then append the type struct data into an array authVecSlice. Below is the code type AuthVectors struct { MessageType string `json:"message_type"` IMSIstring `json:"IMSI"` RANDstring `json:"RAND"` XRESstring `json:"XRES"` AUTNstring `json:"AUTN"` } var imsistr = "2443411" var authVecSlice = make([]AuthVectors, 10) func getAuthVec() { hostName := "localhost" portNum := "4343" service := hostName + ":" + portNum RemoteAddr, err := net.ResolveUDPAddr("udp", service) conn, err := net.DialUDP("udp", nil, RemoteAddr) if err != nil { log.Fatal(err) } defer conn.Close() // write a message to server _, err = conn.Write([]byte(imsistr)) if err != nil { log.Println(err) } // receive message from server buffer := make([]byte, 1024) i, _, err := conn.ReadFromUDP(buffer) checkError(err) err = json.Unmarshal(buffer[:i], ) if err != nil { panic(err) } authVecSlice = append(authVecSlice, avs) fmt.Println(authVecSlice) } The array out put is as follows [{AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} {AUTN_PARAM 2443411 211B025CB1CC8EE9CBB5FC7F56C1506B C9396A5AC7E68D62 31D...} {AUTN_PARAM 2443411 7D2A8C6E6B5CA243278987DFAF7FC829 C9EE960D0F5A501A 7E8..} ...] I would like to use the field RAND to search and return the corresponding XRES in the array. For example in the array is {AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} I would like to use the RAND value for example C98FC7C6DE9E1351A397D0AF99B6E890 as a search string and return its corresponding XRES D857E39D57E5E6BE. func getXRES(a []AuthVectors, x interface{}) (xres string) { for _, v := range a { if x == v { xres := v.XRES return xres } } return "Item not found" } The problem for me is that the array value do not have key to be use to perform the search. All example I found involves the use of key to fetch the values. Any help -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/a2f7571c-7742-4586-840c-0c52db839a45%40googlegroups.com.
[go-nuts] How to search for string value in array
I have trying to write a function that will accept a string as an input and return another string in a slice but it not working. I have function that unmarshal udp response to a type AuthVectors and then append the type struct data into an array authVecSlice. Below is the code type AuthVectors struct { MessageType string `json:"message_type"` IMSIstring `json:"IMSI"` RANDstring `json:"RAND"` XRESstring `json:"XRES"` AUTNstring `json:"AUTN"` } var imsistr = "2443411" var authVecSlice = make([]AuthVectors, 10) func getAuthVec() { hostName := "localhost" portNum := "4343" service := hostName + ":" + portNum RemoteAddr, err := net.ResolveUDPAddr("udp", service) conn, err := net.DialUDP("udp", nil, RemoteAddr) if err != nil { log.Fatal(err) } defer conn.Close() // write a message to server _, err = conn.Write([]byte(imsistr)) if err != nil { log.Println(err) } // receive message from server buffer := make([]byte, 1024) i, _, err := conn.ReadFromUDP(buffer) checkError(err) err = json.Unmarshal(buffer[:i], ) if err != nil { panic(err) } authVecSlice = append(authVecSlice, avs) fmt.Println(authVecSlice) } The array out put is as follows [{AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} {AUTN_PARAM 2443411 211B025CB1CC8EE9CBB5FC7F56C1506B C9396A5AC7E68D62 31D...} {AUTN_PARAM 2443411 7D2A8C6E6B5CA243278987DFAF7FC829 C9EE960D0F5A501A 7E8..} ...] I would like to use the field RAND to search and return the corresponding XRES in the array. For example in the array is {AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} I would like to use the RAND value for example C98FC7C6DE9E1351A397D0AF99B6E890 as a search string and return its corresponding XRES D857E39D57E5E6BE. func getXRES(a []AuthVectors, x interface{}) (xres string) { for _, v := range a { if x == v { xres := v.XRES return xres } } return "Item not found" } The problem for me is that the array value do not have key to be use to perform the search. All example I found involves the use of key to fetch the values. Any help -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/729f0972-5637-4a0e-8a7a-283bd8541d71%40googlegroups.com.
[go-nuts] How to search for string value in array
I have trying to write a function that will accept a string as an input and return another string in a slice but it not working. I have function that unmarshal udp response to a type AuthVectors and then append the type struct data into an array authVecSlice. Below is the code type AuthVectors struct { MessageType string `json:"message_type"` IMSIstring `json:"IMSI"` RANDstring `json:"RAND"` XRESstring `json:"XRES"` AUTNstring `json:"AUTN"` } var imsistr = "2443411" var authVecSlice = make([]AuthVectors, 10) func getAuthVec() { hostName := "localhost" portNum := "4343" service := hostName + ":" + portNum RemoteAddr, err := net.ResolveUDPAddr("udp", service) conn, err := net.DialUDP("udp", nil, RemoteAddr) if err != nil { log.Fatal(err) } defer conn.Close() // write a message to server _, err = conn.Write([]byte(imsistr)) if err != nil { log.Println(err) } // receive message from server buffer := make([]byte, 1024) i, _, err := conn.ReadFromUDP(buffer) checkError(err) err = json.Unmarshal(buffer[:i], ) if err != nil { panic(err) } authVecSlice = append(authVecSlice, avs) fmt.Println(authVecSlice) } The array out put is as follows [{AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} {AUTN_PARAM 2443411 211B025CB1CC8EE9CBB5FC7F56C1506B C9396A5AC7E68D62 31D...} {AUTN_PARAM 2443411 7D2A8C6E6B5CA243278987DFAF7FC829 C9EE960D0F5A501A 7E8..} ...] I would like to use the field RAND to search and return the corresponding XRES in the array. For example in the array is {AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} I would like to use the RAND value for example C98FC7C6DE9E1351A397D0AF99B6E890 as a search string and return its corresponding XRES D857E39D57E5E6BE. func getXRES(a []AuthVectors, x interface{}) (xres string) { for _, v := range a { if x == v { xres := v.XRES return xres } } return "Item not found" } The problem for me is that the array value do not have key to be use to perform the search. All example I found involves the use of key to fetch the values. Any help -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/f458b87c-0611-4270-8ee0-ac20019d731c%40googlegroups.com.
[go-nuts] How to search for string value in array
I have trying to write a function that will accept a string as an input and return another string in a slice but it not working. I have function that unmarshal udp response to a type AuthVectors and then append the type struct data into an array authVecSlice. Below is the code type AuthVectors struct { MessageType string `json:"message_type"` IMSIstring `json:"IMSI"` RANDstring `json:"RAND"` XRESstring `json:"XRES"` AUTNstring `json:"AUTN"` } var imsistr = "2443411" var authVecSlice = make([]AuthVectors, 10) func getAuthVec() { hostName := "localhost" portNum := "4343" service := hostName + ":" + portNum RemoteAddr, err := net.ResolveUDPAddr("udp", service) conn, err := net.DialUDP("udp", nil, RemoteAddr) if err != nil { log.Fatal(err) } defer conn.Close() // write a message to server _, err = conn.Write([]byte(imsistr)) if err != nil { log.Println(err) } // receive message from server buffer := make([]byte, 1024) i, _, err := conn.ReadFromUDP(buffer) checkError(err) err = json.Unmarshal(buffer[:i], ) if err != nil { panic(err) } authVecSlice = append(authVecSlice, avs) fmt.Println(authVecSlice) } The array out put is as follows [{AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} {AUTN_PARAM 2443411 211B025CB1CC8EE9CBB5FC7F56C1506B C9396A5AC7E68D62 31D...} {AUTN_PARAM 2443411 7D2A8C6E6B5CA243278987DFAF7FC829 C9EE960D0F5A501A 7E8..} ...] I would like to use the field RAND to search and return the corresponding XRES in the array. For example in the array is {AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} I would like to use the RAND value for example C98FC7C6DE9E1351A397D0AF99B6E890 as a search string and return its corresponding XRES D857E39D57E5E6BE. func getXRES(a []AuthVectors, x interface{}) (xres string) { for _, v := range a { if x == v { xres := v.XRES return xres } } return "Item not found" } The problem for me is that the array value do not have key to be use to perform the search. All example I found involves the use of key to fetch the values. Any help -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/c07c7b2b-7aac-41cd-ab83-1db3cc7435c6%40googlegroups.com.
[go-nuts] How to search for string value in array
I have trying to write a function that will accept a string as an input and return another string in a slice but it not working. I have function that unmarshal udp response to a type AuthVectors and then append the type struct data into an array authVecSlice. Below is the code type AuthVectors struct { MessageType string `json:"message_type"` IMSIstring `json:"IMSI"` RANDstring `json:"RAND"` XRESstring `json:"XRES"` AUTNstring `json:"AUTN"` } var imsistr = "2443411" var authVecSlice = make([]AuthVectors, 10) func getAuthVec() { hostName := "localhost" portNum := "4343" service := hostName + ":" + portNum RemoteAddr, err := net.ResolveUDPAddr("udp", service) conn, err := net.DialUDP("udp", nil, RemoteAddr) if err != nil { log.Fatal(err) } defer conn.Close() // write a message to server _, err = conn.Write([]byte(imsistr)) if err != nil { log.Println(err) } // receive message from server buffer := make([]byte, 1024) i, _, err := conn.ReadFromUDP(buffer) checkError(err) err = json.Unmarshal(buffer[:i], ) if err != nil { panic(err) } authVecSlice = append(authVecSlice, avs) fmt.Println(authVecSlice) } The array out put is as follows [{AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} {AUTN_PARAM 2443411 211B025CB1CC8EE9CBB5FC7F56C1506B C9396A5AC7E68D62 31D...} {AUTN_PARAM 2443411 7D2A8C6E6B5CA243278987DFAF7FC829 C9EE960D0F5A501A 7E8..} ...] I would like to use the field RAND to search and return the corresponding XRES in the array. For example in the array is {AUTN_PARAM 2443411 C98FC7C6DE9E1351A397D0AF99B6E890 D857E39D57E5E6BE 8000...} I would like to use the RAND value for example C98FC7C6DE9E1351A397D0AF99B6E890 as a search string and return its corresponding XRES D857E39D57E5E6BE. func getXRES(a []AuthVectors, x interface{}) (xres string) { for _, v := range a { if x == v { xres := v.XRES return xres } } return "Item not found" } The problem for me is that the array value do not have key to be use to perform the search. All example I found involves the use of key to fetch the values. Any help -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/b653494b-83c3-438c-bf42-170f526bd369%40googlegroups.com.
[go-nuts] How to perform dynamic unmarsahlling
Can anyone help me perform dynamic unmarshalling depending on the type of messages received from a diameter client. In the code below, I have to two structures which represent two different messages received by a diameter server. I would like to modify the current code which unmarshals the request to the struct `var req HandleDERRequest` such that the unmarshalling is done dynamically either to the `var req HandleDERRequest` or `var challreq HandleChallRequest`, depending on the received message that matches a particular structure. I have tried to implement with the code below but it not working as it should. All the answers are being return at the same time and this is not what am expecting. func HandleDER(settings sm.Settings) diam.HandlerFunc { // If received AVP messages are of this struct format, Unmarshal message to this structure type HandleDERRequest struct { SessionID datatype.UTF8String `avp:"Session-Id"` OriginHostdatatype.DiameterIdentity `avp:"Origin-Host"` OriginRealm datatype.DiameterIdentity `avp:"Origin-Realm"` DestinationHost datatype.DiameterIdentity `avp:"Destination-Host"` DestinationRealm datatype.DiameterIdentity `avp:"Destination-Realm"` UserName datatype.UTF8String `avp:"User-Name"` AuthSessionState datatype.Enumerated `avp:"Auth-Session-State"` AuthApplicationID datatype.Unsigned32 `avp:"Auth-Application-Id"` AuthRequestType datatype.Enumerated `avp:"Auth-Request-Type"` EAPPayloaddatatype.OctetString `avp:"EAP-Payload"` RATType datatype.Enumerated `avp:"RAT-Type"` ANID datatype.UTF8String `avp:"ANID"` } // If received AVP messages are of this struct format, Unmarshal message to this structure type HandleChallRequest struct { SessionIDdatatype.UTF8String `avp:"Session-Id"` OriginHost datatype.DiameterIdentity `avp:"Origin-Host"` OriginRealm datatype.DiameterIdentity `avp:"Origin-Realm"` DestinationHost datatype.DiameterIdentity `avp:"Destination-Host"` DestinationRealm datatype.DiameterIdentity `avp:"Destination-Realm"` EAPPayload datatype.OctetString `avp:"EAP-Payload"` } return func(c diam.Conn, m *diam.Message) { var err error = nil var req HandleDERRequest var code uint32 = diam.Success err = m.Unmarshal() if err != nil { err = fmt.Errorf("Unmarshal failed: %s", err) code = diam.UnableToComply log.Printf("Invalid DER(%d): %s\n", code, err.Error()) } a := m.Answer(code) a.NewAVP(avp.SessionID, avp.Mbit, 0, req.SessionID) a.NewAVP(avp.OriginHost, avp.Mbit, 0, req.DestinationHost) a.NewAVP(avp.OriginRealm, avp.Mbit, 0, req.DestinationRealm) a.NewAVP(avp.OriginStateID, avp.Mbit, 0, settings.OriginStateID) _, err = AKA_Challenge_Request(settings, c, a) if err != nil { log.Printf("Failed to send AAA challenge request: %s", err.Error()) } var challreq HandleChallageRequest err = m.Unmarshal() if err != nil { err = fmt.Errorf("Unmarshal failed: %s", err) code = diam.UnableToComply log.Printf("Invalid DER(%d): %s\n", code, err.Error()) } a = m.Answer(code) a.NewAVP(avp.SessionID, avp.Mbit, 0, req.SessionID) a.NewAVP(avp.OriginHost, avp.Mbit, 0, req.DestinationHost) a.NewAVP(avp.OriginRealm, avp.Mbit, 0, req.DestinationRealm) a.NewAVP(avp.OriginStateID, avp.Mbit, 0, settings.OriginStateID) _, err = AKA_Success_Notification(settings, c, a) if err != nil { log.Printf("Failed to send Success Notification: %s", err.Error()) } } } I know there should be an if condition of the return function but I don't know how to start. Please any idea about how to go about it. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/ec15b55e-a927-4bc7-a8ea-cc9f172df506%40googlegroups.com.
[go-nuts] How to Unmarshal diameter client different request to different struct at diamter server side
Hi, Am developing a diameter server using go-diameter package that need to perform EAP-AKA authentication. In the DER/DEA process, the client will be sending multiple request to the server, that is first the client sends an identity request to the server, the server respond with RAND, MAC, etc to the client, the client then sends second request to the server, in this case with different parameters(RES, MAC, etc) to the server. The server need to handle the second request using the same handle if am right since in DER/DEA, the server handle only DER. My question is how can i handle the second request coming from the client using the same handle(DER) at the diameter server side. That using the same DER handle to response to diameter client multiple request. Depending on the received message the server unmarshal the set of AVPs to the right structure. Is it possible, if possible any help. Currently i have at the server side this request handle //First server response to cleint should containg this payload func AKA_Challenge_Request(settings sm.Settings, w io.Writer, m *diam.Message) (n int64, err error) { PayloadSlice := []byte(`RAND, AUTHN, MAC, RESULT_ID`) m.NewAVP(avp.EAPPayload, avp.Mbit, 0, datatype.OctetString(PayloadSlice)) return m.WriteTo(w) } //Second server response to cleint should containg this payload func AKA_Success_Notification(settings sm.Settings, w io.Writer, m *diam.Message) (n int64, err error) { EAPSlice := []byte(`EAP_Success`) MSKSlice := []byte(`EAP-Master-Session-Key`) m.NewAVP(avp.EAPPayload, avp.Mbit, 0, datatype.OctetString(EAPSlice)) m.NewAVP(avp.EAPMasterSessionKey, avp.Mbit, 0, datatype.OctetString(MSKSlice)) return m.WriteTo(w) } // Handle funtion at the server side func HandleDER(settings sm.Settings) diam.HandlerFunc { // If received AVP messages are of this struct format, Unmarshal message to this structure type HandleDERRequest struct { SessionID datatype.UTF8String `avp:"Session-Id"` OriginHostdatatype.DiameterIdentity `avp:"Origin-Host"` OriginRealm datatype.DiameterIdentity `avp:"Origin-Realm"` DestinationHost datatype.DiameterIdentity `avp:"Destination-Host"` DestinationRealm datatype.DiameterIdentity `avp:"Destination-Realm"` UserName datatype.UTF8String `avp:"User-Name"` AuthSessionState datatype.Enumerated `avp:"Auth-Session-State"` AuthApplicationID datatype.Unsigned32 `avp:"Auth-Application-Id"` AuthRequestType datatype.Enumerated `avp:"Auth-Request-Type"` EAPPayloaddatatype.OctetString `avp:"EAP-Payload"` RATType datatype.Enumerated `avp:"RAT-Type"` ANID datatype.UTF8String `avp:"ANID"` } // If received AVP messages are of this struct format, Unmarshal message to this structure type HandleDERRequest struct { SessionID datatype.UTF8String `avp:"Session-Id"` OriginHostdatatype.DiameterIdentity `avp:"Origin-Host"` OriginRealm datatype.DiameterIdentity `avp:"Origin-Realm"` DestinationHost datatype.DiameterIdentity `avp:"Destination-Host"` DestinationRealm datatype.DiameterIdentity `avp:"Destination-Realm"` EAPPayloaddatatype.OctetString `avp:"EAP-Payload"` } return func(c diam.Conn, m *diam.Message) { var err error = nil var req HandleDERRequest var code uint32 = diam.Success err = m.Unmarshal() if err != nil { err = fmt.Errorf("Unmarshal failed: %s", err) code = diam.UnableToComply log.Printf("Invalid DER(%d): %s\n", code, err.Error()) } else { code = diam.Success } fmt.Println(string(req.EAPPayload)) a := m.Answer(code) a.NewAVP(avp.SessionID, avp.Mbit, 0, req.SessionID) a.NewAVP(avp.OriginHost, avp.Mbit, 0, req.DestinationHost) a.NewAVP(avp.OriginRealm, avp.Mbit, 0, req.DestinationRealm) a.NewAVP(avp.OriginStateID, avp.Mbit, 0, settings.OriginStateID) //Respond with first payload _, err = AKA_Challenge_Request(settings, c, a) if err != nil { log.Printf("Failed to send AAA challenge request: %s", err.Error()) } } } Any help? -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/441a6c77-ec50-4a9c-833e-2e4bce1d0b79%40googlegroups.com.
[go-nuts] How to handle diamter client different request with one handle at diamter server side
Hi, Am developing a diameter server using go-diameter package that need to perform EAP-AKA authentication. In the DER/DEA process, the client will be sending multiple request to the server, that is first the client sends an identity request to the server, the server respond with RAND, MAC, etc to the client, the client then sends second request to the server, in this case with different parameters(RES, MAC, etc) to the server. The server need to handle the second request using the same handle if am right since in DER/DEA, the server handle only DER. My question is how can i handle the second request coming from the client using the same handle(DER) at the diameter server side. That using the same DER handle to response to diameter client multiple request. Is it possible, if possible any help. Currently i have at the server side this request handle //First server response to cleint should containg this payload func AKA_Challenge_Request(settings sm.Settings, w io.Writer, m *diam.Message) (n int64, err error) { PayloadSlice := []byte(`RAND, AUTHN, MAC, RESULT_ID`) m.NewAVP(avp.EAPPayload, avp.Mbit, 0, datatype.OctetString(PayloadSlice)) return m.WriteTo(w) } //Second server response to cleint should containg this payload func AKA_Success_Notification(settings sm.Settings, w io.Writer, m *diam.Message) (n int64, err error) { EAPSlice := []byte(`EAP_Success`) MSKSlice := []byte(`EAP-Master-Session-Key`) m.NewAVP(avp.EAPPayload, avp.Mbit, 0, datatype.OctetString(EAPSlice)) m.NewAVP(avp.EAPMasterSessionKey, avp.Mbit, 0, datatype.OctetString(MSKSlice)) return m.WriteTo(w) } // Handle funtion at the server side func HandleDER(settings sm.Settings) diam.HandlerFunc { type HandleDERRequest struct { SessionID datatype.UTF8String `avp:"Session-Id"` OriginHostdatatype.DiameterIdentity `avp:"Origin-Host"` OriginRealm datatype.DiameterIdentity `avp:"Origin-Realm"` DestinationHost datatype.DiameterIdentity `avp:"Destination-Host"` DestinationRealm datatype.DiameterIdentity `avp:"Destination-Realm"` UserName datatype.UTF8String `avp:"User-Name"` AuthSessionState datatype.Enumerated `avp:"Auth-Session-State"` AuthApplicationID datatype.Unsigned32 `avp:"Auth-Application-Id"` AuthRequestType datatype.Enumerated `avp:"Auth-Request-Type"` EAPPayloaddatatype.OctetString `avp:"EAP-Payload"` RATType datatype.Enumerated `avp:"RAT-Type"` ANID datatype.UTF8String `avp:"ANID"` } return func(c diam.Conn, m *diam.Message) { var err error = nil var req HandleDERRequest var code uint32 = diam.Success err = m.Unmarshal() if err != nil { err = fmt.Errorf("Unmarshal failed: %s", err) code = diam.UnableToComply log.Printf("Invalid DER(%d): %s\n", code, err.Error()) } else { code = diam.Success } fmt.Println(string(req.EAPPayload)) a := m.Answer(code) a.NewAVP(avp.SessionID, avp.Mbit, 0, req.SessionID) a.NewAVP(avp.OriginHost, avp.Mbit, 0, req.DestinationHost) a.NewAVP(avp.OriginRealm, avp.Mbit, 0, req.DestinationRealm) a.NewAVP(avp.OriginStateID, avp.Mbit, 0, settings.OriginStateID) //Respond with first payload _, err = AKA_Challenge_Request(settings, c, a) if err != nil { log.Printf("Failed to send AAA challenge request: %s", err.Error()) } } } Any help? -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/e36ba859-85c9-4d03-aad4-2c7935d8a570%40googlegroups.com.
Re: [go-nuts] How to query mysql hexadecimal data
Hi hex.EncodeString works! The problem was the struct field types ([]byte) instead of string. Thanks! On Wednesday, September 4, 2019 at 4:49:46 PM UTC+3, burak serdar wrote: > > On Wed, Sep 4, 2019 at 6:41 AM > > wrote: > > > > > > I have tried to query mysql database table data but am getting the byte > data after trying many instances to convert the byte data to the > hexadecimal values. Any help about how can i get the hexadecimal values > from the database. > > > > I created the table below as > > > > > > CREATE TABLE `subscriber_profile` ( > > > > `msin` binary(5) NOT NULL, > > `msisdn` bigint(16) NOT NULL, > > `k` binary(16) DEFAULT NULL, > > `opc` binary(16) DEFAULT NULL, > > `sqn` binary(6) DEFAULT NULL, > >... > > PRIMARY KEY (`mcc`,`mnc`,`msin`) > > ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; > > > > And the data in the database as > > > > > > INSERT INTO subscriber_profile VALUES > (...,35850001/msisdn/,0x000102030405060708090A0B0C0D0E0F/k/,0xBC2BCE2A23BE2FAE32E4F1B4546004F7/opc/,...); > > > > > > Am querying the table using msisdn as parameter. Also is using byte in > struct field right? > > > > > > type SubscriberProfile struct { > > ... > > Msisdn int`json:"msisdn"` > > K []byte `json:"k"` > > Opc[]byte `json:"opc"` > > } > > > > func GetPara(msisdn int) []SubscriberProfile { > > db := dbConn() > > selDB, err := db.Query("SELECT msisdn, k, opc FROM > subscriber_profile WHERE msisdn=?;", msisdn) > > if err != nil { > > panic(err.Error()) > > } > > av := SubscriberProfile{} > > res := []SubscriberProfile{} > > for selDB.Next() { > > var msisdn int > > var k, opc []byte > > err = selDB.Scan(, , ) > > if err != nil { > > panic(err.Error()) > > } > > > > av.Msisdn = msisdn > > av.K = k > > av.Opc = opc > > res = append(res, av) > > } > > return res > > } > > > > I have tried to use hex.EncodeToString(k) but could not get the right > result. > > > > var data []SubscriberProfile > > data = GetPara(35850001) > > > > fmt.Println(data) > > > > output: > > [{0 0 0 35850001 [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] [188 43 206 > 42 35 190 47 174 50 228 241 180 84 96 4 247]}] > > > > > > Am expecting an output [{0 0 0 35850001 > 000102030405060708090A0B0C0D0E0F BC2BCE2A23BE2FAE32E4F1B4546004F7 0 ...}] > > > > Any help? > > The output you got is already the same as your expected output, with > the difference that the byte arrays are printed as decimal values > enclosed with [ ]. Instead of fmt.Println, print the struct fields one > by one while hex-encoding the contents of the byte arrays to get what > you need. What was the problem with hex.EncodeString? > > > > > > > > > > -- > > You received this message because you are subscribed to the Google > Groups "golang-nuts" group. > > To unsubscribe from this group and stop receiving emails from it, send > an email to golan...@googlegroups.com . > > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/fd3a967e-2b02-4658-a27b-ccfd40aa125d%40googlegroups.com. > > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/2d4d7200-979c-4105-b35d-bfd84117fb0b%40googlegroups.com.
[go-nuts] how to query mysql hexadecimal value
I have tried to query mysql database table data but am getting the byte data after trying many instances to convert the byte data to the hexadecimal values. Any help about how can i get the hexadecimal values from the database. I created the table below as CREATE TABLE `subscriber_profile` ( `msin` binary(5) NOT NULL, `msisdn` bigint(16) NOT NULL, `k` binary(16) DEFAULT NULL, `opc` binary(16) DEFAULT NULL, `sqn` binary(6) DEFAULT NULL, ... PRIMARY KEY (`mcc`,`mnc`,`msin`)) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; And the data in the database as INSERT INTO subscriber_profile VALUES (...,35850001/*msisdn* /,0x000102030405060708090A0B0C0D0E0F/*k* /,0xBC2BCE2A23BE2FAE32E4F1B4546004F7/*opc*/,...); Am querying the table using msisdn as parameter. Also is using byte in struct field right? type SubscriberProfile struct { ... Msisdn int`json:"msisdn"` K []byte `json:"k"` Opc[]byte `json:"opc"`} func GetPara(msisdn int) []SubscriberProfile { db := dbConn() selDB, err := db.Query("SELECT msisdn, k, opc FROM subscriber_profile WHERE msisdn=?;", msisdn) if err != nil { panic(err.Error()) } av := SubscriberProfile{} res := []SubscriberProfile{} for selDB.Next() { var msisdn int var k, opc []byte err = selDB.Scan(, , ) if err != nil { panic(err.Error()) } av.Msisdn = msisdn av.K = k av.Opc = opc res = append(res, av) } return res} I have tried to use hex.EncodeToString(k) but could not get the right result. var data []SubscriberProfile data = GetPara(35850001) fmt.Println(data) output:[{0 0 0 35850001 [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] [188 43 206 42 35 190 47 174 50 228 241 180 84 96 4 247]}] Am expecting an output [{0 0 0 35850001 000102030405060708090A0B0C0D0E0F BC2BCE2A23BE2FAE32E4F1B4546004F7 0 ...}] -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4972b387-eb46-4d1b-8a56-3a8fe2d8dbd0%40googlegroups.com.
[go-nuts] Re: Diameter EAP Application - go-diameter
Hi, Yes, i mean “github.com/fiorix/go-diameter” package. <http://github.com/fiorix/go-diameter> I have open an issue asking if it possible https://github.com/fiorix/go-diameter <https://www.google.com/url?q=https%3A%2F%2Fgithub.com%2Ffiorix%2Fgo-diameter=D=1=AFQjCNHz3r2z9EyWyPmhhjDnBHkI4mZ7Eg> . Thanks for the hint. Abraham On Wednesday, August 28, 2019 at 10:28:16 AM UTC+3, Afriyie Abraham Kwabena wrote: > > Hi All, > > It it possible to modify the go-diameter package to implement Diameter EAP > Application, that is > instead of the current capabilities exchange request and answer, CER/CEA > exchange, > i would like to do a DER/DEA request and answer. > If possible how would go about it, which files or part of the diameter > code did i need to modify to > achieve this. > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/9f122b51-7858-4ddf-9d8d-944ea34fccd9%40googlegroups.com.
[go-nuts] Diameter EAP Application - go-diameter
Hi All, It it possible to modify the go-diameter package to implement Diameter EAP Application, that is instead of the current capabilities exchange request and answer, CER/CEA exchange, i would like to do a DER/DEA request and answer. If possible how would go about it, which files or part of the diameter code did i need to modify to achieve this. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/7e06b8dc-e8cc-4eb7-b554-f7b7d924fa71%40googlegroups.com.
[go-nuts] How to create custom diameter application with go
Hi all, I cannot see diameter messages of my custom diameter application (Application-ID 16777255, code: 8388620) in Wireshark after modifying the go-diameter example server and client codes. Can you explain why am not seeing my custom application AVPs in Wireshark? What I did was to write a custom dictionary for my application and load it at both the server and the client, similar to the "hellodictionary" but defining all the application as well. I also modify the client settings to advertise the VendorSpecificApplication which is a group AVP containg the VendorID and ApplicationID AVPs. I modify the hello message request (HMR) and HMA handler at both client and server to contain the AVPs of my custom application (sendPLR/handlePLA). Running the server and the client code and using Wireshark, 1. The transport connection (TCP) was established OK 2. CER/CEA messages were exchanges successfully (Result Code=Success) however, I could not see the "sendPLR" from the client as well as the "handlePLA" response from the server in Wireshark before the DWR/DWA messages. Is modifying the HM the right thing to do to be able to send my custom application AVPs (example MSISDN, IMEI, Location-Type, etc) which I have defined them in my custom dictionary or I have to do something else? Thanks!! -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/55c7c042-ed02-4512-91d6-04e1211d7727%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] go app with both diamter and api interface
Am trying to create an app that can receive an api request and use the api request parameters as input to send a new diameter request to a diamter node. For examplehe diameter interface<- App <-- api interface So the app receive an http request from a client using some url (http://) with some data or url parameters, the app receive the request, retrieve the data or url parameters, use the retrieve data as a diamter AVP input data to send a diameter request to diamter node. The response is also follow the same procedure. Any idea about how can to create this in Go. In GO there is the go-diamter library and also many http server libraries. Is it possible to create this app using these libraries and if yes how i can i do that since the http server handling of requests are different from that of diameter request. Any link to an example or some code example. Any libraries or any other way to create this app in Go? -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4145dafa-664f-4d0e-ac9a-7731fb4090ac%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] how to access request data using global variable -- help
I have this simple http server. How can i access the request data to a global variable and use it in any other part of my application (example in different function). package main import ( "io" "net/http") var data string // Get http request URL data globally and use it in other part of the application func hello(w http.ResponseWriter, r *http.Request) { data := r.URL.Query().Get("somestring")} func main() { mux := http.NewServeMux() mux.HandleFunc("/", hello) http.ListenAndServe(":8000", mux)} -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/55a6f94c-787e-476e-96f5-d3c440f6f024%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] Golang - mongodb watch for specific data
Hi, I have this data or document in mongodb. { "nfInstanceId": "3fa85f64-5717-4562-b3fc-2c963f66af37", "nfType": [ "AMF" ], "nfStatus": [ "string" ], "sNssais": [{ "sst": 1, "sd": "sd1" } ], "nsiList": [ "string" ], "ipv4Addresses": [ "198.51.100.100" ], "allowedNssais": [{ "sst": 0, "sd": "string" }], "priority": 0, "load": 0, "amfInfo": { "amfSetId": "3fa85f64-5717-4562-b3fc-2c963f66afbb", "taiList": [{ "plmnId": { "mcc": "string", "mnc": "string" }, "tac": "string" }], "n2InterfaceAmfInfo": { "ipv4EndpointAddress": [ "198.51.100.100" ] } } } Can anyone help me write a golang change stream to get notification for this data when there is an update to this concument using the nfType key as filter. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: [go-nuts] How to apply middleware
Hi, Yes this make sense and it works. The code also look simple to read. Thanks!! On Thursday, April 4, 2019 at 7:54:27 PM UTC+3, car...@hotmail.com wrote: > > How about something like this? Unsure about concurrent access to global > variables, but if you want to access srv and clientstore from package sw, > It'd make sense to me to move srv and clientstore out of main and into a > package. > > howToApplyMiddleware > main.go > - server > server.go > - sw > handler.go > router.go > middleware.go > > //main.go > package main > > import ( > "log" > "net/http" > "howToApplyMiddleware/sw" > ) > > func main() { > log.Printf("Server started") > log.Fatal(http.ListenAndServe(":8000", sw.Router)) > } > > > //server.go > package server > > import ( > "gopkg.in/oauth2.v3/errors" > "gopkg.in/oauth2.v3/manage" > "gopkg.in/oauth2.v3/server" > "gopkg.in/oauth2.v3/store" > "log" > ) > > var ClientStore *store.ClientStore > var SRV *server.Server > > func init() { > ClientStore = store.NewClientStore() > manager := manage.NewDefaultManager() > manager.SetAuthorizeCodeTokenCfg(manage.DefaultAuthorizeCodeTokenCfg) > manager.MapClientStorage(ClientStore) > manager.SetRefreshTokenCfg(manage.DefaultRefreshTokenCfg) > manager.MustTokenStorage(store.NewMemoryTokenStore()) > > SRV = server.NewDefaultServer(manager) > SRV.SetAllowGetAccessRequest(true) > SRV.SetClientInfoHandler(server.ClientFormHandler) > > SRV.SetInternalErrorHandler(func(err error) (re *errors.Response) { > log.Println("Internal Error:", err.Error()) > return > }) > > SRV.SetResponseErrorHandler(func(re *errors.Response) { > log.Println("Response Error:", re.Error.Error()) > }) > } > > > //handler.go > package sw > > import ( > "net/http" > ) > > //Funtion in handler.go in subdir > > func protecteduri(w http.ResponseWriter, r *http.Request) { > w.Write([]byte("Hello, I'm protected")) > } > > > //middleware.go > package sw > > import ( > "net/http" > "howToApplyMiddleware/server" > ) > > //This function in middleware.go in subdir > > func validateToken(f func(http.ResponseWriter, *http.Request)) > func(http.ResponseWriter, *http.Request) { > return func(w http.ResponseWriter, r *http.Request) { > _, err := server.SRV.ValidationBearerToken(r) > if err != nil { > http.Error(w, err.Error(), http.StatusBadRequest) > return > } > f(w, r) > > } > } > > > //router.go > package sw > > import ( > "encoding/json" > "fmt" > "github.com/google/uuid" > "github.com/gorilla/mux" > "gopkg.in/oauth2.v3/models" > "net/http" > "howToApplyMiddleware/server" > "strings" > ) > > var Router *mux.Router > > func init() { > Router = NewRouter() > Router.HandleFunc("/oauth2/token", func(w http.ResponseWriter, r > *http.Request) { > server.SRV.HandleTokenRequest(w, r) > }) > > Router.HandleFunc("/credentials", func(w http.ResponseWriter, r > *http.Request) { > clientId := uuid.New().String()[:8] > clientSecret := uuid.New().String()[:8] > err := server.ClientStore.Set(clientId, { > ID: clientId, > Secret: clientSecret, > Domain: "http://localhost:9094;, > }) > if err != nil { > fmt.Println(err.Error()) > } > > w.Header().Set("Content-Type", "application/json") > json.NewEncoder(w).Encode(map[string]string{"CLIENT_ID": clientId, > "CLIENT_SECRET": clientSecret}) > }) > } > > type Route struct { > Namestring > Method string > Pattern string > HandlerFunc http.HandlerFunc > } > > type Routes []Route > > func NewRouter() *mux.Router { > router := mux.NewRouter().StrictSlash(true) > for _, route := range routes { > var handler http.Handler > handler = route.HandlerFunc > //handler = Logger(handler, route.Name) > > router. > Methods(route.Method). > Path(route.Pattern). > Name(route.Name). > Handler(handler) > } > > return router > } > > func Index(w http.ResponseWriter, r *http.Request) { > fmt.Fprintf(w, "Hello World!") > } > > var routes = Routes{ > { > "Index", > "GET", > "/", > Index, > }, > > { > "protecteduri", > strings.ToUpper("Get"), > "/protected", > validateToken(protecteduri), > }, > } > > > On Thursday, April 4, 2019 at 4:44:14 AM UTC-4, afriyie...@gmail.com > wrote: >> >> I have modify the middleware to the below but it only work if the handler >> function "/protected" is in the main function. >> I have many handlers and do not want to put all of them in the main.go. >> You suggest i define a struct and use member function of the struct, can >> you elaborate more about for me or the format. >> >> func ValidateToken(srv *server.Server) func(http.Handler) http.Handler { >> return func(next http.Handler) http.Handler { >> return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { >> notAuth := []string{"/oauth2/token", "/credentials"} //List of endpoints >> that doesn't require auth >> requestPath := r.URL.Path//current request >> path >> >> //check if request does not need authentication, serve the request if it >> doesn't need it >> for _, value := range notAuth { >> >> if value == requestPath { >>
Re: [go-nuts] How to apply middleware
I have modify the middleware to the below but it only work if the handler function "/protected" is in the main function. I have many handlers and do not want to put all of them in the main.go. You suggest i define a struct and use member function of the struct, can you elaborate more about for me or the format. func ValidateToken(srv *server.Server) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { notAuth := []string{"/oauth2/token", "/credentials"} //List of endpoints that doesn't require auth requestPath := r.URL.Path//current request path //check if request does not need authentication, serve the request if it doesn't need it for _, value := range notAuth { if value == requestPath { next.ServeHTTP(w, r) return } } _, err := srv.ValidationBearerToken(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } next.ServeHTTP(w, r) }) } } On Thursday, April 4, 2019 at 10:46:08 AM UTC+3, afriyie...@gmail.com wrote: > > changing and using "router.Use(getTokenMW(server))" is validating all the > routes. How can i exclude routes > /oauth2/token and /credentials. I read that populate but i dont get the > idea. > Any clew about how to go about this? > > On Wednesday, April 3, 2019 at 6:47:12 PM UTC+3, Burak Serdar wrote: >> >> On Wed, Apr 3, 2019 at 8:35 AM wrote: >> >> > type Route struct { >> > Namestring >> > Method string >> > Pattern string >> > HandlerFunc http.HandlerFunc >> > } >> > >> > type Routes []Route >> > >> > func NewRouter() *mux.Router { >> > router := mux.NewRouter().StrictSlash(true) >> > for _, route := range routes { >> > var handler http.Handler >> > handler = route.HandlerFunc >> > handler = Logger(handler, route.Name) >> > >> > router. >> > Methods(route.Method). >> > Path(route.Pattern). >> > Name(route.Name). >> > Handler(handler) >> > } >> > >> > return router >> > } >> > >> > func Index(w http.ResponseWriter, r *http.Request) { >> > fmt.Fprintf(w, "Hello World!") >> > } >> > >> > var routes = Routes{ >> > { >> > "Index", >> > "GET", >> > "/", >> > Index, >> > }, >> > >> > { >> > "protecteduri", >> > strings.ToUpper("Get"), >> > "/protected", >> > protecteduri, >> > }, >> > } >> > >> > My question is how do i apply the "validateToken" function (middleware) >> to the routes in the router.go? >> > The function is to validate the access token in the request message >> before calling the handler functions. >> > >> Have you looked at the gorilla/mux documentation about middlewares? >> There are examples there: https://godoc.org/github.com/gorilla/mux >> >> You need to change the validateToken func: >> >> func getTokenMW(srv *server.Server) func(http.Handler) http.Handler { >>return func(next http.Handler) http.Handler { >> return http.HandlerFunc(func(w http.ResponseWriter, r >> *http.Request) { >> } >>} >> } >> >> Then: >> router.Use(getTokenMW(server)) >> >> Or, you can define a struct, put the server pointer in it, and use a >> member function of that struct as the middleware. >> > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: [go-nuts] How to apply middleware
changing and using "router.Use(getTokenMW(server))" is validating all the routes. How can i exclude routes /oauth2/token and /credentials. I read that populate but i dont get the idea. Any clew about how to go about this? On Wednesday, April 3, 2019 at 6:47:12 PM UTC+3, Burak Serdar wrote: > > On Wed, Apr 3, 2019 at 8:35 AM > > wrote: > > > type Route struct { > > Namestring > > Method string > > Pattern string > > HandlerFunc http.HandlerFunc > > } > > > > type Routes []Route > > > > func NewRouter() *mux.Router { > > router := mux.NewRouter().StrictSlash(true) > > for _, route := range routes { > > var handler http.Handler > > handler = route.HandlerFunc > > handler = Logger(handler, route.Name) > > > > router. > > Methods(route.Method). > > Path(route.Pattern). > > Name(route.Name). > > Handler(handler) > > } > > > > return router > > } > > > > func Index(w http.ResponseWriter, r *http.Request) { > > fmt.Fprintf(w, "Hello World!") > > } > > > > var routes = Routes{ > > { > > "Index", > > "GET", > > "/", > > Index, > > }, > > > > { > > "protecteduri", > > strings.ToUpper("Get"), > > "/protected", > > protecteduri, > > }, > > } > > > > My question is how do i apply the "validateToken" function (middleware) > to the routes in the router.go? > > The function is to validate the access token in the request message > before calling the handler functions. > > > Have you looked at the gorilla/mux documentation about middlewares? > There are examples there: https://godoc.org/github.com/gorilla/mux > > You need to change the validateToken func: > > func getTokenMW(srv *server.Server) func(http.Handler) http.Handler { >return func(next http.Handler) http.Handler { > return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) > { > } >} > } > > Then: > router.Use(getTokenMW(server)) > > Or, you can define a struct, put the server pointer in it, and use a > member function of that struct as the middleware. > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] How to apply middleware
Hi, I have this main function in a main.go file inside the main directory func main() { log.Printf("Server started") router := sw.NewRouter() manager := manage.NewDefaultManager() manager.SetAuthorizeCodeTokenCfg(manage.DefaultAuthorizeCodeTokenCfg) manager.MustTokenStorage(store.NewMemoryTokenStore()) clientStore := store.NewClientStore() manager.MapClientStorage(clientStore) srv := server.NewDefaultServer(manager) srv.SetAllowGetAccessRequest(true) srv.SetClientInfoHandler(server.ClientFormHandler) manager.SetRefreshTokenCfg(manage.DefaultRefreshTokenCfg) srv.SetInternalErrorHandler(func(err error) (re *errors.Response) { log.Println("Internal Error:", err.Error()) return }) srv.SetResponseErrorHandler(func(re *errors.Response) { log.Println("Response Error:", re.Error.Error()) }) router.HandleFunc("/oauth2/token", func(w http.ResponseWriter, r *http.Request) { srv.HandleTokenRequest(w, r) }) router.HandleFunc("/credentials", func(w http.ResponseWriter, r *http.Request) { clientId := uuid.New().String()[:8] clientSecret := uuid.New().String()[:8] err := clientStore.Set(clientId, { ID: clientId, Secret: clientSecret, Domain: "http://localhost:9094;, }) if err != nil { fmt.Println(err.Error()) } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{"CLIENT_ID": clientId, "CLIENT_SECRET": clientSecret}) }) log.Fatal(http.ListenAndServe(":8000", router)) } The functions below are in different files in the sub directory of the main as *maindir *subdir //Funtion in handler.go in subdir func protecteduri(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, I'm protected")) } //This function in middleware.go in subdir func validateToken(f http.HandlerFunc, srv *server.Server) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, err := srv.ValidationBearerToken(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } f.ServeHTTP(w, r) }) } And my routes are in the router.go in the subdir as type Route struct { Namestring Method string Pattern string HandlerFunc http.HandlerFunc } type Routes []Route func NewRouter() *mux.Router { router := mux.NewRouter().StrictSlash(true) for _, route := range routes { var handler http.Handler handler = route.HandlerFunc handler = Logger(handler, route.Name) router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(handler) } return router } func Index(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } var routes = Routes{ { "Index", "GET", "/", Index, }, { "protecteduri", strings.ToUpper("Get"), "/protected", protecteduri, }, } My question is how do i apply the "validateToken" function (middleware) to the routes in the router.go? The function is to validate the access token in the request message before calling the handler functions. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] Re: How to rewrite code and apply middleware gorilla mux routes
On Wednesday, April 3, 2019 at 11:28:55 AM UTC+3, afriyie...@gmail.com wrote: > > Hi > > I have this working main function code and would like to rewrite it such > that the middleware "validateToken" would be applied > to all my gorilla mux routes. > Please attached is the file containg the working code. > > What i would like to do is to use the handler function > > http.HandleFunc("/protected", validateToken(func(w http.ResponseWriter, r > *http.Request) { > w.Write([]byte("Hello, I'm protected" > outside the main function as > func protecteduri(w http.ResponseWriter, r *http.Request) { > w.Write([]byte("Hello, I'm protected")) > } > > and apply the middleware function "validateToken" to all my gorilla mux > routes so that the token used to request can be validated. The routes > type Route struct { > Namestring > Method string > Pattern string > HandlerFunc http.HandlerFunc > } > > type Routes []Route > > func NewRouter() *mux.Router { > router := mux.NewRouter().StrictSlash(true) > for _, route := range routes { > var handler http.Handler > handler = route.HandlerFunc > handler = Logger(handler, route.Name) > > router. > Methods(route.Method). > Path(route.Pattern). > Name(route.Name). > Handler(handler) > } > > return router > } > > func Index(w http.ResponseWriter, r *http.Request) { > fmt.Fprintf(w, "Hello World!") > } > > var routes = Routes{ > { > "Index", > "GET", > "/", > Index, > }, > > { > "protecteduri", > strings.ToUpper("Get"), > "/protected", > protecteduri, > }, > > { > "AccessTokenRequest", > strings.ToUpper("Post"), > "/oauth2/token", > AccessTokenRequest, > }, > } > > Can anyone help? > > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] Re: How to rewrite code and apply middleware gorilla mux routes
On Wednesday, April 3, 2019 at 11:28:55 AM UTC+3, afriyie...@gmail.com wrote: > > Hi > > I have this working main function code and would like to rewrite it such > that the middleware "validateToken" would be applied > to all my gorilla mux routes. > Please attached is the file containg the working code. > > What i would like to do is to use the handler function > > http.HandleFunc("/protected", validateToken(func(w http.ResponseWriter, r > *http.Request) { > w.Write([]byte("Hello, I'm protected" > outside the main function as > func protecteduri(w http.ResponseWriter, r *http.Request) { > w.Write([]byte("Hello, I'm protected")) > } > > and apply the middleware function "validateToken" to all my gorilla mux > routes so that the token used to request can be validated. The routes > type Route struct { > Namestring > Method string > Pattern string > HandlerFunc http.HandlerFunc > } > > type Routes []Route > > func NewRouter() *mux.Router { > router := mux.NewRouter().StrictSlash(true) > for _, route := range routes { > var handler http.Handler > handler = route.HandlerFunc > handler = Logger(handler, route.Name) > > router. > Methods(route.Method). > Path(route.Pattern). > Name(route.Name). > Handler(handler) > } > > return router > } > > func Index(w http.ResponseWriter, r *http.Request) { > fmt.Fprintf(w, "Hello World!") > } > > var routes = Routes{ > { > "Index", > "GET", > "/", > Index, > }, > > { > "protecteduri", > strings.ToUpper("Get"), > "/protected", > protecteduri, > }, > > { > "AccessTokenRequest", > strings.ToUpper("Post"), > "/oauth2/token", > AccessTokenRequest, > }, > } > > Can anyone help? > Sorry please attacted is the file -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout. main.go Description: Binary data
[go-nuts] How to rewrite code and apply middleware gorilla mux routes
Hi I have this working main function code and would like to rewrite it such that the middleware "validateToken" would be applied to all my gorilla mux routes. Please attached is the file containg the working code. What i would like to do is to use the handler function http.HandleFunc("/protected", validateToken(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, I'm protected" outside the main function as func protecteduri(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, I'm protected")) } and apply the middleware function "validateToken" to all my gorilla mux routes so that the token used to request can be validated. The routes type Route struct { Namestring Method string Pattern string HandlerFunc http.HandlerFunc } type Routes []Route func NewRouter() *mux.Router { router := mux.NewRouter().StrictSlash(true) for _, route := range routes { var handler http.Handler handler = route.HandlerFunc handler = Logger(handler, route.Name) router. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(handler) } return router } func Index(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } var routes = Routes{ { "Index", "GET", "/", Index, }, { "protecteduri", strings.ToUpper("Get"), "/protected", protecteduri, }, { "AccessTokenRequest", strings.ToUpper("Post"), "/oauth2/token", AccessTokenRequest, }, } Can anyone help? -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] How to write bson.M format Golang
Hi, Am using mongodb as database. Am able to query the database from the command line using the command db.nfinstances.distinct("ipv4Addresses",{"nfType":"AMF", "amfInfo.amfSetId": "3fa85f64-5717-4562-b3fc-2c963f66af33"}) and this give me ipaddress [x.x.x.x] output that i want. mongo command line Output: *> db.nfinstances.distinct("ipv4Addresses",{"nfType":"AMF", "amfInfo.amfSetId": "3fa85f64-5717-4562-b3fc-2c963f66af33"})* *[ "198.51.100.300" ]* *> * However if i query using the golang query var SliceIP []NfInstance db.C(COLLECTION).Find("nfType": "AMF", "amfInfo.amfSetId": "3fa85f64-5717-4562-b3fc-2c963f66af33").Distinct("ipv4Addresses", ) am getting empy array instead of the the IP address in an array. In the database i have the json document as { "nfinstanceID": "3fa85f64-5717-4562-b3fc-2c963f66af33", "nfType": [ "AMF" ], "nfStatus": [ "REGISTERED" ], "sNssais": [ { "sst": 1, "sd": "sd1" } ], "nsiList": [ "string" ], "ipv4Addresses": [ "198.51.100.300" ], "allowedNssais": [ { "sst": 1, "sd": "sd1" } ], "amfInfo": { "amfSetId": "3fa85f64-5717-4562-b3fc-2c963f66af33", "taiList": [ { "plmnId": { "mcc": "244", "mnc": "38" }, "tac": "string" } ], "n2InterfaceAmfInfo": { "ipv4EndpointAddress": [ "198.51.100.105" ] } } } Can anyone help me find the problem. I may be doing missing something. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] Help - Mongodb JSON access
Hi, I have a json data in mongodb in the format be bellow, i need help to access the data using the "nfinstanceID" which is a uuid string ID part of an api request for example example "http://localhost:5050/nnrf-nfm/v1/nf-instances/3fa85f64-5717-4562-b3fc-2c963f66afaa; The api route is of the form "".../nnrf-nfm/v1/nf-instances/{nfinstanceID}" instead of using "bson.ObjectId". My struct is in the format type NfInstance struct { ID bson.ObjectId `bson:"_id" json:"id"` ValidityPeriod int `json:"validityPeriod" bson:"validityPeriod"` NfInstanceID string`json:"nfinstanceID" bson:"nfinstanceID"` SNssais[]Snssai `json:"sNssais" bson:"sNssais"` NfServices []Service `json:"nfServices" bson:"nfServices"` ... } type Service struct { ServiceInstanceID string`json:"serviceInstanceId" bson:"serviceInstanceId"` Versions []Version `json:"versions" bson:"versions"` } type Version struct { APIVersionInURI string`json:"apiVersionInUri" bson:"apiVersionInUri"` ... } type Snssai struct { Sst int32 `json:"sst"` . } // Fuctions are // Find a instance by its id func (m *NfInstanceDataAccess) FindById(id string) (NfInstance, error) { var nfinstance NfInstance err := db.C(COLLECTION).FindId(bson.ObjectIdHex(id)).One() return nfinstance, err } // Handler function func NfInstancebyIdGet(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["nfinstanceID"] nfinstance, err := da.FindById(id) if err != nil { respondWithError(w, http.StatusBadRequest, "Invalid nfinstance ID") return } respondWithJson(w, http.StatusOK, nfinstance) } Using this functions work but i would like to access the data not using bson.ObjectId but rather "nfinstanceID" part. Completely new to golang. Thanks in advance!! Abraham { "id": "5c6c238dfdde24520f7b1b69", "validityPeriod": 1, "nfinstanceID": "3fa85f64-5717-4562-b3fc-2c963f66afaa", "heartBeatTimer": 0, "nfType": "string", "nfStatus": [ "REGISTERED" ], "sNssais": [ { "sst": 0, "sd": "string" } ], "nsiList": [ "string" ], "nfServices": [ { "serviceInstanceId": "string", "versions": [ { "apiVersionInUri": "http://{apiRoot}/v1/xxx;, "apiFullVersion": "string", "expiry": "2019-02-03T14:08:56.65+02:00" } ] } ] } -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] Re: loop - Help
hi, currently am able to get the vlaues but will like to get both key and values, how will i be able to do it. This is output i got now, a slice of the apiVersionInUri", which is corent but want it with the keys, like "apiVersionInUri": "http://instance4.com";, map form [ "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com/home;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://instance4.com;, "http://localhost.com.test; ] On Thursday, February 14, 2019 at 2:33:43 PM UTC+2, afriyie...@gmail.com wrote: > > Hi, > > Am quite new in go language and asking for help. > I have this JSON object in mongodb with collection name "COLLECTION", > I have multiple object in the database (mongo) and would like to access > all the string > values """apiVersionInUri": "string", in all the objects. > Can anyone help me do this in Golang. I know i will need a for loop to > achieve this but > i dont know how to go about it. > > Thanks in advance > > //Example JSON object look like this > > > { > "nfInstanceId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", > "heartBeatTimer": 0, > "sNssais": [ > { > "sst": 0, > "sd": "string" > } > ], > "nsiList": [ > "string" > ], > "nfServices": [ > { > "serviceInstanceId": "string", > "versions": [ > { > "apiVersionInUri": "string", > "apiFullVersion": "string", > "expiry": "2019-02-03T12:08:56.650Z" > } > ] > } > ] > } > > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] Re: loop - Help
hi, This is what i have done so far but still need some help as to how to return ""v.APIVersionInURI" in the loop function (FindAlluris()) . Am trying to write a function which will return all the field ""v.APIVersionInURI" in the mongo db and then use this function in my API handler function. I have tried this // The strut look like this type NfInstance struct { ID bson.ObjectId `bson:"_id" json:"id"` NfServices []Service `json:"nfServices" bson:"nfServices"` .. } type Service struct { Versions []Version `json:"versions" bson:"versions"` .. } type Version struct { APIVersionInURI string`json:"apiVersionInUri" bson:"apiVersionInUri"` ... } // Establish a connection to database func (m *NfInstanceDataAccess) Connect() { session, err := mgo.Dial(m.Server) if err != nil { log.Fatal(err) } db = session.DB(m.Database) } // Find list of nfinstances URIs func (m *NfInstanceDataAccess) FindAlluris() (NfInstance, error) { nfInstance := NfInstance{} itr := db.C(COLLECTION).Find(bson.M{}).Iter() for itr.Next() { for _, svc := range nfInstance.NfServices { for _, v := range svc.Versions { fmt.Println(v.APIVersionInURI) } } } if err := itr.Close(); err != nil { fmt.Println(err) } } but dont know where to return all "v.APIVersionInURI" strings. The handler function look like this // Get all database URIs func NfInstanceUrlsGet(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=UTF-8") uris, err := da.FindAlluris() if err != nil { respondWithError(w, http.StatusInternalServerError, err.Error()) return } respondWithJson(w, http.StatusOK, uris) } Thanks in advance On Thursday, February 14, 2019 at 2:33:43 PM UTC+2, afriyie...@gmail.com wrote: > > Hi, > > Am quite new in go language and asking for help. > I have this JSON object in mongodb with collection name "COLLECTION", > I have multiple object in the database (mongo) and would like to access > all the string > values """apiVersionInUri": "string", in all the objects. > Can anyone help me do this in Golang. I know i will need a for loop to > achieve this but > i dont know how to go about it. > > Thanks in advance > > //Example JSON object look like this > > > { > "nfInstanceId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", > "heartBeatTimer": 0, > "sNssais": [ > { > "sst": 0, > "sd": "string" > } > ], > "nsiList": [ > "string" > ], > "nfServices": [ > { > "serviceInstanceId": "string", > "versions": [ > { > "apiVersionInUri": "string", > "apiFullVersion": "string", > "expiry": "2019-02-03T12:08:56.650Z" > } > ] > } > ] > } > > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] loop - Help
Hi, Am quite new in go language and asking for help. I have this JSON object in mongodb with collection name "COLLECTION", I have multiple object in the database (mongo) and would like to access all the string values """apiVersionInUri": "string", in all the objects. Can anyone help me do this in Golang. I know i will need a for loop to achieve this but i dont know how to go about it. Thanks in advance //Example JSON object look like this { "nfInstanceId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "heartBeatTimer": 0, "sNssais": [ { "sst": 0, "sd": "string" } ], "nsiList": [ "string" ], "nfServices": [ { "serviceInstanceId": "string", "versions": [ { "apiVersionInUri": "string", "apiFullVersion": "string", "expiry": "2019-02-03T12:08:56.650Z" } ] } ] } -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: [go-nuts] Help- Empty request header and body
Hi, Please attacted is app files (unnecessary codes deleted). I don’t if I could made mode simpler but this is how am able let you identify the problem am encountering when I run this code. I tried to print the request header and body and this is what am getting ] &{{ObjectIdHex("") 0 0 [] [] []}} 2019/02/11 14:38:16 panic: ObjectIDs must be exactly 12 bytes long (got 0) 2019/02/11 14:38:16 [PUT] "/nnrf-nfm/v1/nf-instances/3fa85f64-5717-4562-b3fc-2c963f66afa6" 775.484µs Thanks in advance On Monday, February 11, 2019 at 11:29:05 AM UTC+2, Lutz Horn wrote: > > > Am new in golang and am trying to write an API but my request header and > > body is always empty. > > Well, that's a *lot* of code. Please trim it so it forms a SSCCE > (http://www.sscce.org/). > > Lutz > > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout. <>
[go-nuts] array output null - help
Hi, Am trying to write a simple api using gorm and Sqlite3 database. Am using stuct and functions below. However, after "PUT" of JSON format payload using Postman, the instances get created but when try to "GET" all the instances, the array content shows "plmnList : null" without the array key and values even though i have provided values in the JSON PUT body. Help needed, maybe am doing some wrong. Thanks in advance. example of PUT json payload using Postman { "nfInstanceId": "3fa85f64-5717-4562-b3fc-2c96322333", "plmnList":[{ "mcc": "446", "mnc": "336" }], "validityPeriod":44 } // Struct type NfInstanceStore struct { NfInstanceID string `json:"nfInstanceId" gorm:"primary_key"` PlmnList [ ]PlmnList `json:"plmnList"` ValidityPeriod int`json:" validityPeriod"` } type PlmnList struct { gorm.Model Mcc string `json:"mcc"` Mnc string `json:"mnc"` } // Database migration var db *gorm.DB var e error func initialMigration() { db, e := gorm.Open("sqlite3", "gorm.db") if e != nil { fmt.Println(e.Error()) panic("failed to connect database") } defer db.Close() // Migrate the schema db.AutoMigrate({}, {}) } // Main function is as follow func main() { initialMigration() router := mux.NewRouter() router.HandleFunc("/nnrf-nmf/v1/nf-instances", getAllNFInstances).Methods("GET") router.HandleFunc("/nnrf-nmf/v1/nf-instances/{nfinstanceID}", registerNewNFInstance).Methods("PUT") } // PUT - registerNewNFInstance func registerNewNFInstance(w http.ResponseWriter, r *http.Request) { db, err := gorm.Open("sqlite3", "gorm.db") if err != nil { panic("failed to connect database") } defer db.Close() nfinstance := model.NfInstanceStore{} decoder := json.NewDecoder(r.Body) if err := decoder.Decode(); err != nil { respondError(w, http.StatusBadRequest, err.Error()) return } defer r.Body.Close() if err := db.Save().Error; err != nil { respondError(w, http.StatusInternalServerError, err.Error()) return } respondJSON(w, http.StatusCreated, nfinstance) } // GETAll func getAllNFInstances(w http.ResponseWriter, r *http.Request) { db, err := gorm.Open("sqlite3", "gorm.db") if err != nil { panic("failed to connect database") } defer db.Close() nfinstances := []model.NfInstanceStore{} db.Find() respondJSON(w, http.StatusOK, nfinstances) } // func respondJSON(w http.ResponseWriter, status int, payload interface{}) { response, err := json.Marshal(payload) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) w.Write([]byte(response)) } -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] Patch method
Hi, Am new in Go programming and need help to write a PATCH method for my go-server. my data field look like these type NFProfile struct { NFType string `json:"nftype"` NFInstanceID string `json:"instanceid"` NFStatus string `json:"nfstatus"` ID string `json:"id"` } //Create NFProfile DB type NFProfileDB struct { nfprofiles map[string]NFProfile } Can anyone tell me what to and if there is any library to do this such that i can use poastman to send PATCH request to the server. Thanks in advance Abraham -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
[go-nuts] oauth2 for openAPI
Hi, am new to go language and need help or ideas as how i can write a server oauth2 to have a client authenticated.. If there is an already code or if i have to write my own then please help with the guidlines of how write it The client have to send a POST request and get authenticated and then the server respond with the 200 success. The format of the API oauth2 in json is attached bellow. { "openapi": "3.0.0", "info": { "version": "1.PreR15.1.0", "title": "NRF OAuth2", "description": "MYSERVER OAuth2 Authorization" }, "paths": { "/oauth2/token": { "post": { "summary": "Access Token Request", "operationId": "AccessTokenRequest", "tags": [ "Access Token Request" ], "security": [ { "basic": [] } ], "requestBody": { "content": { "application/x-www-form-urlencoded": { "schema": { "$ref": "#/components/schemas/AccessTokenReq" } } }, "required": true }, "responses": { "200": { "description": "Successful Access Token Request", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/AccessTokenRsp" } } }, "headers": { "Cache-Control": { "$ref": "#/components/headers/cache-control" }, "Pragma": { "$ref": "#/components/headers/pragma" } } }, "400": { "description": "Error in the Access Token Request", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/AccessTokenErr" } } }, "headers": { "Cache-Control": { "$ref": "#/components/headers/cache-control" }, "Pragma": { "$ref": "#/components/headers/pragma" } } } } } } }, "components": { "securitySchemes": { "basic": { "type": "http", "scheme": "basic" } }, "headers": { "cache-control": { "required": true, "schema": { "type": "string", "enum": [ "no-store" ] } }, "pragma": { "required": true, "schema": { "type": "string", "enum": [ "no-cache" ] } } }, "schemas": { "AccessTokenReq": { "format": "x-www-form-urlencoded", "required": [ "grant_type", "nfInstanceId", "nfType", "targetNfType", "scope" ], "properties": { "grant_type": { "type": "string", "enum": [ "client_credentials" ] }, "nfInstanceId": { "$ref": "TS29571_CommonData.yaml#/components/schemas/NfInstanceId" }, "nfType": { "$ref": "TS29510_Nnrf_NFManagement.yaml#/components/schemas/NFType" }, "targetNfType": { "$ref": "TS29510_Nnrf_NFManagement.yaml#/components/schemas/NFType" }, "scope": null, "type": "string\npattern: '^([a-zA-Z0-9_]*[*]{0,1})$'" } }, "AccessTokenRsp": { "type": "object", "required": [ "access_token", "token_type" ], "properties": { "access_token": { "type": "string", "description": "JWS Compact Serialized representation of JWS signed JSON object (AccessTokenClaims)" }, "token_type": { "type": "string" }, "expires_in": { "type": "integer" }, "scope": { "type": "string", "pattern": "^([a-zA-Z0-9_]*[*]{0,1})$" } } }, "AccessTokenClaims": { "type": "object", "required": [ "issuer", "subject", "audience", "scope", "expiration" ], "properties": { "issuer": { "$ref": "TS29571_CommonData.yaml#/components/schemas/NfInstanceId" }, "subject": { "type": "string" }, "audience": { "type": "array", "items": { "$ref": "TS29571_CommonData.yaml#/components/schemas/NfInstanceId" } }, "scope": { "type": "string", "pattern": "^([a-zA-Z0-9_]*[*]{0,1})$" }, "expiration": { "type": "integer" } } }, "AccessTokenErr": { "type": "object", "required": [ "error" ], "properties": { "error": { "type": "string", "enum": [ "invalid_request", "invalid_client", "invalid_grant", "unauthorized_client", "unsupported_grant_type", "invalid_sope" ] }, "error_description": { "type": "string" }, "error_uri": { "type": "string" } } } } }, "externalDocs": { "description": "Documentation", "url": "http://www.3gpp.org/ftp/Specs/archive/29_series/29.510/; } } BR Abraham -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.